使用连接从两个表中选择数据时,如何从一行中获取mysql查询中的数据?
"id" "itemId" "itemTempId" "itemName" "userId" "postId"
"1" "US1" "T001" "Samsung Galaxy Note 5" "1" "1"
"id" "itemId" "itemTempId" "itemImageName" "userId" "postId"
"1" "US1" "T001" "front.jpg" "1" "1"
"2" "US1" "T001" "side-left.jpg" "1" "1"
"3" "US1" "T001" "side-right.jpg" "1" "1"
"4" "US1" "T001" "back.jpg" "1" "1"
现在,当我在下面选择第一个表中的1行和第二个表中的相关行时,我会得到每一行中的所有数据,当我使用php打印时,它也会重复。
select a.itemName, b.itemImageName from amga a left join amgb b on a.userId = b.userId where a.userId = 1;
当前输出
"itemName" "itemImageName"
"Samsung Galaxy Note 5" "front.jpg"
"Samsung Galaxy Note 5" "side-left.jpg"
"Samsung Galaxy Note 5" "side-right.jpg"
"Samsung Galaxy Note 5" "back.jpg"
理想输出或其他一些不会重复itemName且可以使用php轻松输出的变体。
"itemName" "itemImageName"
"Samsung Galaxy Note 5" "front.jpg","side-left.jpg","side-right.jpg","back.jpg"
在最终结果中,标题仅输出一次,而图像名称需要循环播放。像这样:
"Samsung Galaxy Note 5"
"front.jpg","side-left.jpg","side-right.jpg","back.jpg"
答案 0 :(得分:2)
select a.itemName, GROUP_CONCAT(b.itemImageName)
from amga a
left join amgb b
on a.userId = b.userId
where a.userId = 1
group by a.itemName
如果您不想复制,请在GROUP_CONCAT中使用DISTINCT。
答案 1 :(得分:2)
您需要使用GROUP_CONCAT
功能进行分组。请尝试此查询:
select a.itemName, group_concat(b.itemImageName)
from amga a left join amgb b on a.userId = b.userId
where a.userId = 1
group by a.itemName;
答案 2 :(得分:2)
group_concat
运算符是您正在寻找的内容:
SELECT item_name, GROUP_CONCAT(item_image_name)
FROM amga
LEFT JOIN amgb ON amga.userId = b.userId
WHERE amge.userId = 1
GROUP BY item_name