简体   繁体   English

如何在mysql查询中连接行

[英]how do I concatenate rows in a mysql query

table 1
--------
pid | name
1    someone
2    another


table2
--------
bid | valu
1     drum
2     guitar
3     flower
4     cake


table3
------
id | pid | bid | pref
1    1     3     yes
2    1     1     maybe
3    1     2     no
4    2     4     definately
5    2     2   
6    2     3     no

So as you can see I have 3 simple tables where the third one is used to create a mapping between table 1 and 2 along with some additional data. 因此,您可以看到我有3个简单的表,其中第三个用于创建表1和表2之间的映射以及一些其他数据。 Now I need to write a query to display the valu and pref in a concatenated string based on the pid , 现在我需要编写一个查询来显示基于pid的连接字符串中的valupref

So against pid = 1 , the expected output is something like flower yes, drum maybe, guitar no ....so How do I write this query? 因此,对于pid = 1 ,预期的输出就像flower yes, drum maybe, guitar no ....所以我该如何写这个查询?

I tried( pretty much a blind guess): 我尝试过(几乎是盲目猜测):

SELECT opa.name, GROUP_CONCAT(CONCAT(opb.valu,' ',opc.pref) SEPARATOR ',') AS myChoice
 From
     table_1 opa
 INNER JOIN table_3 opc ON opc.pid = opa.pid
 INNER JOIN table_2 opb ON opb.bid = opc.bid

Any help is appreciated. 任何帮助表示赞赏。

your query is right you just forgot the GROUP BY 你的查询是对的,你只是忘记了GROUP BY

 SELECT opa.name, GROUP_CONCAT(CONCAT(opb.valu,' ',opc.pref) SEPARATOR ',') AS myChoice
 From
 table1 opa
 INNER JOIN table3 opc ON opc.pid = opa.pid
 INNER JOIN table2 opb ON opb.bid = opc.bid
 group by opc.pid

DEMO HERE 在这里演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM