[英]MySQL \ join 2 tables and show results from 2 rows in one column
I have 2 tables. 我有2张桌子。 One is a list of proucts, and the second - list of images connected to each product.
第一个是产品列表,第二个是连接到每个产品的图像列表。
PRODUCTS as P 产品为P
ID | NAME
1 | apple
2 | plum
3 | carrot
4 | strawberry
5 | pie
IMAGES as IM IMAGES作为IM
PRODUCT_ID | IMAGE | I_NAME
1 | 1 | app_abc.jpg
1 | 2 | apple.jpg
1 | 3 | appleonemoretime.jpg
2 | 1 | plum.jpg
2 | 2 | plum2.jpg
2 | 3 | plum3.jpg
2 | 4 | plum4.jpg
3 | 1 | somecarrot.jpg
4 | 1 | s1.jpg
etc... 等等...
Additional info: 附加信息:
- Each product has min 1 image. -每个产品至少要有1张图片。
- The max amount of images connected with one product is 60. I would like to get: list of products with image names (one row = one product) . -与一种产品关联的最大图像数量为60。我想要得到:具有图像名称的产品列表(一行=一种产品) 。
- I will search products by product.id - I want to get images in one column , separated by commas, I do not want to get 60 'null' columns. -我将按product.id搜索产品-我想在一列中获取图片 ,用逗号分隔, 我不想获取60个“空”列。
For instance: if I search of p.id (1, 3) I would like to get something like: 例如:如果我搜索p.id(1,3),我想得到类似以下内容:
P.ID | IM1.I_NAME
1 | app_abc.jpg, apple.jpg, appleonemoretime.jpg
3 | somecarrot.jpg
Is there a way? 有办法吗? 'COALESCE' is good for this?
'COALESCE'对这个有好处吗?
What I have now is: 我现在所拥有的是:
select p.id
from products p
join images im on im.product_id = p.id
where p.id in (1, 3)
You can use group_concat
in query. 您可以在查询中使用
group_concat
。 Try this query, 试试这个查询,
select p.id, group_concat(im.I_NAME)
from products p
join images im on im.product_id = p.id
where p.id in (1, 3)
group by p.id
you can use GROUP_CONCAT
function 您可以使用
GROUP_CONCAT
函数
reference: https://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat 参考: https : //dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat
尝试这个 :
select p.id, group_concat(im.I_NAME separator ',') from products p left join images im on im.product_id = p.id where p.id in (1, 3) group by p.id
GROUP_CONCAT is your best friend, your query should look like this: GROUP_CONCAT是您最好的朋友,您的查询应如下所示:
SELECT p.id, GROUP_CONCAT( im.i_name SEPARATOR '; ' ) AS images
FROM products p
LEFT JOIN images im ON (im.product_id = p.id)
WHERE p.id IN (1, 3) GROUP BY p.id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.