我的查询有问题: 所以,我有一个表呼叫供应商:
ref_article supplier_id
1903 10
我有另一张表格礼物:
id_gift etat id_adresse ref_article
100455 3 1 1903
100456 3 2 1903
100457 3 3 1903
我有桌子gift_adresse:
id name surname
1 jkkjl hkj
2 hjhjk jklj
3 kjkj hjjkhk
我的查询是这样的:
SELECT
supp.ref_article,
COUNT(g.id_instant_gagnant) AS gifts_number
FROM supplier supp
LEFT JOIN gift g ON supp.ref_article = g.ref_article
INNER JOIN gift_adresse g_adr ON g.id_adresse = g_adr.id_adresse
WHERE supp.supplier_id = 10 AND g_ig.etat = 3
GROUP BY g.ref_article
对于此查询,我得到:
ref_article gifts_number
1903 3
问题是我希望为我的示例获取此ref_article的所有id_gift
:100455,100456,100457
是否可以在单个查询中进行?
答案 0 :(得分:1)
您可以使用GROUP_CONCAT(expr)
获取所需的CSV输出。
MySQL解决方案:
SELECT
supp.ref_article
, COUNT(g.id_instant_gagnant) AS gifts_number
, GROUP_CONCAT(g.id_gift) AS gift_ids
FROM supplier supp
LEFT JOIN gift g ON supp.ref_article = g.ref_article
INNER JOIN gift_adresse g_adr ON g.id_adresse = g_adr.id_adresse
WHERE supp.supplier_id = 10
AND g_ig.etat = 3
GROUP BY g.ref_article
答案 1 :(得分:1)
直接问题的答案是group_concat()
。但是,您的查询相当尴尬:
SELECT supp.ref_article,
COUNT(g.id_instant_gagnant) AS gifts_number
FROM supplier supp LEFT JOIN
-------------------^ LEFT JOIN is turned to inner join
gift g
ON supp.ref_article = g.ref_article INNER JOIN
gift_adresse g_adr
ON g.id_adresse = g_adr.id_adresse
--------^ by this expression here
WHERE supp.supplier_id = 10 AND g_ig.etat = 3
--------------------------------^ I don't know what this is
GROUP BY g.ref_article
---------^ Don't aggregate by a `LEFT JOIN`ed table unless you want `NULL` values *AND* this is not the expression in the `FROM`
我建议免除LEFT JOIN
,修复表中的引用,并删除第三个表:
SELECT supp.ref_article,
COUNT(g.id_instant_gagnant) AS gifts_number,
GROUP_CONCAT(g.id_gift) as gifts
FROM supplier supp JOIN
gift g
ON supp.ref_article = g.ref_article and g.etat = 3
WHERE supp.supplier_id = 10
GROUP BY supp.ref_article
如果你想要一个LEFT JOIN
,你现在可以重新加入。etat
上的条件位于ON
子句中,它需要在那里。