SELECT
A.*,GROUP_CONCAT(B.`TEXT`) `TEXT`
FROM
table_a A INNER JOIN table_b B USING (ID)
WHERE A.ID=2;
这是一个示例
mysql> DROP TABLE IF EXISTS table_a;
Query OK, 0 rows affected (0.03 sec)
mysql> DROP TABLE IF EXISTS table_b;
Query OK, 0 rows affected (0.03 sec)
mysql> CREATE TABLE table_a
-> (ID int not null auto_increment,
-> NAME VARCHAR(20),primary key (ID));
Query OK, 0 rows affected (0.13 sec)
mysql> CREATE TABLE table_b
-> (ID int not null,`TEXT` TEXT,key (ID));
Query OK, 0 rows affected (0.06 sec)
mysql> INSERT INTO table_a (NAME) VALUES ('DAN'),('RON'),('JANE');
Query OK, 3 rows affected (0.06 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> INSERT INTO table_b (ID,`TEXT`) VALUES
-> (2,'APPLE'),(2,'BANANA'),(2,'COFFEE');
Query OK, 3 rows affected (0.05 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT A.*,GROUP_CONCAT(B.`TEXT`) `TEXT`
-> FROM table_a A INNER JOIN table_b B USING (ID) WHERE A.ID=2;
+----+------+---------------------+
| ID | NAME | TEXT |
+----+------+---------------------+
| 2 | RON | APPLE,BANANA,COFFEE |
+----+------+---------------------+
1 row in set (0.00 sec)
试试看 !!!
要获取 table_a 中可用的所有值以及可以从 table_b 分组的任何值:
SELECT
A.*,IFNULL(GROUP_CONCAT(B.`TEXT`),'') `TEXT`
FROM
table_a A LEFT JOIN table_b B USING (ID)
GROUP BY A.ID
这是该示例:
mysql> use test
Database changed
mysql> DROP TABLE IF EXISTS table_a;
Query OK, 0 rows affected (0.03 sec)
mysql> DROP TABLE IF EXISTS table_b;
Query OK, 0 rows affected (0.02 sec)
mysql> CREATE TABLE table_a (ID int not null auto_increment,NAME VARCHAR(20),primary key (ID));
Query OK, 0 rows affected (0.01 sec)
mysql> CREATE TABLE table_b (ID int not null,`TEXT` TEXT,key (ID));
Query OK, 0 rows affected (0.03 sec)
mysql> INSERT INTO table_a (NAME) VALUES ('DAN'),('RON'),('JANE');
Query OK, 3 rows affected (0.02 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> INSERT INTO table_b (ID,`TEXT`) VALUES (2,'APPLE'),(2,'BANANA'),(2,'COFFEE');
Query OK, 3 rows affected (0.00 sec)
Records: 3 Duplicates: 0 Warnings: 0
mysql> SELECT A.*,IFNULL(GROUP_CONCAT(B.`TEXT`),'') `TEXT`
-> FROM table_a A LEFT JOIN table_b B USING (ID) GROUP BY A.ID;
+----+------+---------------------+
| ID | NAME | TEXT |
+----+------+---------------------+
| 1 | DAN | |
| 2 | RON | APPLE,BANANA,COFFEE |
| 3 | JANE | |
+----+------+---------------------+
3 rows in set (0.00 sec)
mysql>