[英]Complexe sql query from multiple tables
I have a problem with my query: So, I have a table call supplier: 我的查询有问题:因此,我有一个表格呼叫供应商:
ref_article supplier_id
1903 10
I have another table call gift: 我还有另一个餐桌礼物:
id_gift etat id_adresse ref_article
100455 3 1 1903
100456 3 2 1903
100457 3 3 1903
And I have the table gift_adresse: 我有一个表gift_adresse:
id name surname
1 jkkjl hkj
2 hjhjk jklj
3 kjkj hjjkhk
My query is like this: 我的查询是这样的:
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
For this query I get: 对于此查询,我得到:
ref_article gifts_number
1903 3
The problem is that I want to get all id_gift
for this ref_article for my example : 100455,100456,100457 Is it possible to do in a single query? 问题是我想为我的示例获取此ref_article的所有
id_gift
:100455,100456,100457是否可以在单个查询中执行?
You can use GROUP_CONCAT(expr)
for the desired CSV output. 您可以将
GROUP_CONCAT(expr)
用于所需的CSV输出。
MySQL Solution : 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
The answer to your direct question is group_concat()
. 您直接问题的答案是
group_concat()
。 However, your query is rather awkward: 但是,您的查询很尴尬:
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`
I would suggest dispensing with the LEFT JOIN
, fixing the references in the table, and removing the third table: 我建议放弃
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
If you want a LEFT JOIN
, you can now add it back in. The condition on etat
is in the ON
clause, where it would need to be. 如果需要
LEFT JOIN
,现在可以将其重新添加etat
上的条件位于ON
子句中,该子句所在的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.