将两个连接表和一个数据表返回到用GROUP CONCAT分隔的字符串逗号

时间:2015-09-22 19:53:26

标签: mysql sql

从这些表中:

 table_a
 id | date       | owner | space
 1  |  85408503  |  4    |  5
 2  |  52345234  |  5    |  5
 3  |  52345243  |  2    |  5

 table_b
 id | name     | age
 2  |  luis    |  32
 4  |  german  |  53
 5  |  marta   |  43

 table_c
 id | c_id       | stack |  vs 
 1  |     3      |  1    |   2
 2  |     3      |  4    |   2
 3  |     1      |  1    |   2
 4  |     3      |  4    |   3

我想在table_a.space中选择具有特定编号的每个字段(例如table_a.space = 5)GROUP BY t1.id与table_b.name连接,其中owner = table_b.id和包含连接的新列用逗号分隔巧合:table_a.id = table_c.c_id table_c.version = 2

所以..我的尝试(我尝试使用group by,using等很多东西,但没有成功

所以只有什么能正常运行

 SELECT t1.id,t1.owner,t3.vs      
 FROM table_a t1 LEFT JOIN table_b t2 ON t1.owner = t2.id 
 LEFT JOIN table_c t3 ON t1.id = t3.c_id 
 WHERE t1.space = 5 GROUP BY t1.id ORDER BY t1.id

我知道这会放入一个字符串(如果我把它放在" t1.owner之后,"它只会返回一行

 GROUP_CONCAT(DISTINCT t3.stack SEPARATOR ',') as selected     

我不知道t3.vs的巧合在哪里

 AND t3.vs = 2

我想在t1.space = 5

时返回
id  |  owner| space | vs | selected  
 2  |  5    |  5    |  2 |
 3  |  2    |  5    |  2 | 1,4

这时t1.space = 3

这应该返回

id  |  owner| space | vs  |selected  
 3  |  2    |  5    | 2

1 个答案:

答案 0 :(得分:0)

您在问题中间更改了命名约定。你想要的是使用GROUP BY

SELECT t1.id,t1.owner, GROUP_CONCAT(DISTINCT t3.stack SEPARATOR ',') as selected
FROM table_a t1 LEFT JOIN table_b t2 ON t1.owner = t2.id 
LEFT JOIN table_c t3 ON t1.id = t3.c_id 
WHERE t1.space = 5 AND t3.vs=2
GROUP BY t1.id
ORDER BY t1.id

如果没有GROUP BY,您可以将所有内容分组为1行。该组告诉mysql按特定列对其进行分组。