mysql - 来自两个表的多行和来自第二个表列之一的多个值

时间:2017-11-03 09:43:55

标签: mysql sql join

$userid = 1; // got from session
select tableone.userid, tableone.name, tabletwo.action as action
from tableone
leftjoin tabletwo
where tabletwo.userid = $userid
on tableone.jailid = tabletwo.jailid

它从tableone返回all并且全部来自tabletwo,但问题是表2的列之一,即action只返回一个但是在tabletwo中有多个行符合条件(tablewo.userid = $ userid on tableone .jailid = tabletwo.jailid)。

它返回:

userid => 23
name => test title
action => 65

userid => 24
name => test title2
action => 65

我想:

userid => 23
name => test title
action => [65, 66, 67]

userid => 24
name => test title2
action => [76, 57, 34]

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:-2)

您可以将GROUP BYGROUP_CONCAT一起使用,例如:

SELECT tableone.userid, tableone.name, GROUP_CONCAT(tabletwo.action) AS action
FROM tableone
LEFT JOIN tabletwo
ON tableone.jailid = tabletwo.jailid
WHERE tabletwo.userid = $userid
GROUP BY tableone.userid, tableone.name;

Here's GROUP_CONCAT函数的文档。