[英]Join MySQL Tables: Display All Results From Right Table In One Row Of Left Table
Here is some data in table one (persons) 这是表一中的一些数据(人)
Person Table
person_ID | Name | Address
1 | JC | 303 Main Street
2 | NM | 444 Nowhere Drive
And table two (Attribute) 和表二(属性)
Attribute table
person_ID | attribute
1 | dog
1 | cat
2 | bearded
When I join the tables I get the following view: 当我加入表格时,我得到以下视图:
person_id | name | attribute
1 | JC | dog
1 | JC | cat
2 | NM | bearded
Their is a duplicate row from the left table. 它们是左表中的重复行。 It contains the same person_id etc. I want to combine the first two results into one row.
它包含相同的person_id等。我想将前两个结果合并为一行。 Like this:
像这样:
person_id | name | attribute | attribute
1 | JC | dog cat
2 | NM | bearded NULL
or this: 或这个:
person_id | name | attribute
1 | JC | dog, cat
2 | NM | bearded
Here is some of the code I have tried: 这是我尝试过的一些代码:
SELECT person.*,Attribute.att FROM `person`,`Attribute`
WHERE person.`person_id` = Attribute.person_id
AND name = "" group by person_id
Left Join 左加入
Select * from person AS P
LEFT JOIN Attribute AS N
ON P.person_id = N.person_id
Also tried inner join. 还尝试了内部联接。
MySQL has a function GROUP_CONCAT that lets you concatenate rows into a string. MySQL具有功能GROUP_CONCAT ,可让您将行连接为字符串。
Something like this should work: 这样的事情应该起作用:
SELECT person.*, (
SELECT GROUP_CONCAT(attribute SEPARATOR ',')
FROM Attribute
WHERE person.id = Attribute.person_id
) as attributes
FROM `person`
I don't have MySQL on this machine, so I apologize if there are minor mistakes. 我在这台机器上没有MySQL,因此如果有小错误,我深表歉意。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.