This question already has answers here:
JOIN and GROUP_CONCAT with three tables
                                
                                    (2个答案)
                                
                        
                                4年前关闭。
            
                    
我有2张桌子

表A

+-------------------------+
| A_id     unique_id      |
+-------------------------+
| 1         1             |
| 2         1             |
| 3         1             |
| 4         2             |
| 5         2             |
+-------------------------+


表B

+------------------------+
| A_id  unique_id   tags |
+------------------------+
| 1         1         A  |
| 2         1         B  |
| 3         1         c  |
| 4         2         D  |
| 5         2         E  |
+------------------------+


我想加入这些表并获取每个unique_id的所有标签,并且我需要每个a_id的这些串联标签。如何通过具有join和group by和group_concat的单个查询来实现此目的?

o / p

+-----------------+
|  A_id     tags  |
+-----------------+
| 1         A,B,C |
| 2         A,B,C |
| 3         A,B,C |
| 4         D,E   |
| 5         D,E   |
+-----------------+

最佳答案

使用Group_concat或分组依据

select  A_id,
(select Group_concat(tags) From table T1
where  T1.unique_id= T2.unique_id group by unique_id) tags
From table T2

10-05 19:30