2

这在mysql查询中是否可能..

我想选择不同的客户名称,按客户名称分组..

然后显示 group_name 中的值..

table 1

id    client_name   Group_id     
------------------------------
1     IBM               1
2     DELL              1   
3     DELL              2
4     MICROSOFT         3 

table 2

id    group_name
------------------
1     Group1      
2     Group2     
3     Group3  

我需要这样的结果

client_name      merge_group   
-------------------------
IBM                Group1
DELL               Group1, Group2
MICROSOFT          Group3
4

3 回答 3

3

试试这个:

SELECT Client_name, GROUP_CONCAT(group_name) merge_group
FROM Table1 t1
JOIN Table2 t2
  ON t1.group_id = t2.id
GROUP BY t1.Client_name
ORDER BY t1.Id

结果:

╔═════════════╦═══════════════╗
║ CLIENT_NAME ║  MERGE_GROUP  ║
╠═════════════╬═══════════════╣
║ IBM         ║ Group1        ║
║ DELL        ║ Group1,Group2 ║
║ MICROSOFT   ║ Group3        ║
╚═════════════╩═══════════════╝

看到这个 SQLFiddle

于 2013-07-02T07:42:19.523 回答
2

试试这个 ::

Select tab1.id,
GROUP_CONCAT(tab2.group_name SEPARATOR ',') as groupedColumn

from table1 tab1 
inner join table2 tab2 ON tab1.group_id = tab2.id
GROUP BY tab1.Client_name
于 2013-07-02T07:40:49.360 回答
1

试试这个:

SELECT t1.client_name, GROUP_CONCAT(t2.group_name) merge_group 
FROM table1 t1 
INNER JOIN table2 t2 ON t1.Group_id = t2.id
GROUP BY t1.client_name;
于 2013-07-02T07:43:48.950 回答