mysql group_concat在哪里有条件

时间:2018-06-12 10:27:37

标签: mysql

我有三个表产品

ID name
1  A
2  B
3  C

供应商

ID Name
1  V1
2  V2
3  V3

product_vendor

ID pid vid
1  1   1  
2  1   2
3  2   3
4  3   1
5  3   2
6  3   3

我想要左连接并创建如下表所示的响应

p_id  product  vendors
1     A        V1,V2
2     B        V3
3     C        V1,V2,V3
下面是我的解决方案,但它非常复杂。是否可以对此

进行简短查询
SELECT GROUP_CONCAT(v2.`name`) AS vendername,
       p.*,
       GROUP_CONCAT(v.`v_id`) AS vi
FROM `products` p
JOIN `product_vendor` v ON p.id = v.p_id,
                           `vendors` v2
WHERE v2.id IN
    (SELECT GROUP_CONCAT(p.`id`) AS vi
     FROM `vendors` p
     JOIN `product_vendor` v ON p.id = v.p_id
     GROUP BY p.id)
GROUP BY p.id
ORDER BY `p_id` ASC

2 个答案:

答案 0 :(得分:1)

你可以尝试这个,我没有执行查询但认为它会有所帮助:

SELECT `P`.`id`, `P`.`name`, CONCAT(GROUP_CONCAT(CAST(`V`.`name` AS CHAR)), ", ") as vendername 
FROM `product` P 
JOIN `product_vendor` PV ON (`PV`.`pid` = `P`.`id`) 
JOIN `vendor` V ON (`V`.`ID` = `PV`.`vid`) 
GROUP BY `PV`.`pid`

要列出产品表中的所有记录,请使用:

SELECT `P`.`id`, `P`.`name`, CONCAT(GROUP_CONCAT(CAST(`V`.`name` AS CHAR)), ", ") as vendername 
FROM `product` P 
LEFT JOIN `product_vendor` PV ON (`PV`.`pid` = `P`.`id`) 
LEFT JOIN `vendor` V ON (`V`.`ID` = `PV`.`vid`) 
GROUP BY `PV`.`pid`
ORDER BY `P`.`id`

答案 1 :(得分:1)

只需使用联接,group_concat不需要子查询

SELECT 
    p.id, 
    p.name, 
    Group_concat(v.name) AS vendername 
FROM
    product p 
JOIN 
    product_vendor pv ON p.id = pv.pid 
JOIN 
    vendor v ON pv.vid = v.id 
GROUP BY 
    p.id, p.name 
ORDER BY 
    p.id ASC 

Demo