MySQL - 至少有一个东西,大于3个表

时间:2017-07-05 07:33:12

标签: mysql sql

我有3张桌子:

enter image description here

我需要检索1月至少有一种产品销售的卖家的名称,其中1月份该产品的总销售额大于1000。

我想这样开始:

SELECT c.nom, c.prenom 
FROM Commerciaux c
LEFT JOIN Ventes v ON c.id_commerciaux = v.id_commerciaux
WHERE  EXISTS (SELECT 1
FROM Produits p, Ventes v
WHERE p.id_produits = v.id_produits
AND MONTH(v.date) = 1
GROUP BY p.nom
HAVING SUM(v.montant) > 200)
AND MONTH(v.date) = 1
GROUP BY c.nom, c.prenom

WHERE EXISTS中的SELECT似乎正在工作,但是当我必须链接表卖家时,我不知道如何编写它。

任何帮助都会很棒!

3 个答案:

答案 0 :(得分:1)

您可以使用嵌套查询:

   SELECT s.name FROM 
   (Sellers as s JOIN Sales as sp on sp.commercial_id = s.id) JOIN
   Product as p on p.id = sp.product_id
   WHERE MONTH(sp.date) = 1  AND YEAR(sp.date) = 2017 AND    
   (SELECT SUM(Amount) FROM Sales as sp2 WHERE sp2.commercial_id = s.id
    AND sp2.product_id = p.id
    AND MONTH(sp2.date) = 1 AND YEAR(sp2.date) = 2017) > 1000

首先,在外键上加入三个表,然后运行嵌套查询以计算特定产品上所选卖家的金额,以检查是否通过金额限制。

答案 1 :(得分:1)

试试这个

SELECT C.name
FROM Sales A
JOIN Product B ON A.produit_id  = B.id
JOIN Seller C ON A.commercial_id = C.id
WHERE MONTH(A.date) = 1 
HAVING SUM(A.nAmount) > 100
GROUP BY C.name

答案 2 :(得分:1)

您可以使用以下内容:

select distinct s.name
from Sellers s,
    (   -- get all those products that qualify (more than 1000 sales)
        select product_id, sum(amount) as total 
        from Sales 
        where Month(date) = 1
        group by product_id
        having total > 1000
    ) vp,
     Sales sa 
where 
    s.id = sa.commercial_id and
    sa.product_id = vp.id and
    Month(sa.date) = 1
@Leo回答只会返回那些在1月份销售超过100件产品的卖家,而不是退回已售出任何数量超过1000件产品的卖家。< / p>