将两个表连接到一个到多个关系,然后将第二个表连接成一个

时间:2016-09-09 10:07:17

标签: mysql sql

我有两张桌子

users table
id  name 
1   john
2   reaper


users_bid table
id user_id amount
1   1       50
2   1       100
3   2       80
4   1       120

现在我想要一个可以得到以下结果的查询

id  user_id  amount
1     1       50,100,120
2     2        80

2 个答案:

答案 0 :(得分:2)

您需要GROUP_CONCAT()

select T1.id, T2.user_id, group_concat(T2.amount order by T2.amount separator ', ') as amount
from users T1
inner join users_bid T2
on T2.user_id = T1.id
group by T1.id, T2.user_id

答案 1 :(得分:1)

SELECT users.id, users_bid.user_id, users_bid.group_concat(amount) AS amount
FROM users
JOIN users_bid ON users_bid.user_id = users.id
GROUP BY users.id