我有一张存储产品价格信息的表格。它有一列产品ID,数量和折扣。 (用户买2送1英镑,买3送2英镑等。)
我想提取所有与其相关的特定数量折扣的产品。例如,只有购买1,2或3的5英镑,10英镑和20英镑的产品。
我该怎么做?
我希望按产品ID进行分组,其中有三行符合我的条件 - 而且没有其他产品。
答案 0 :(得分:1)
这是SQL Server的查询,可能会对MySql进行一些调整,但这是基础知识。
SELECT * FROM <TABLE> WHERE ProductId in
(SELECT ProductId
FROM <TABLE>
GROUP BY ProductId
HAVING COUNT(ProductId) = 3)
答案 1 :(得分:1)
未经测试(取决于您的架构),但这里的想法是:
SELECT P.id, count(P.id)
FROM products P
LEFT JOIN discounts D ON P.id = D.product_id
WHERE
(D.quantity = 1 AND D.amount = 5)
OR (D.quantity = 2 AND D.amount = 10)
OR (D.quantity = 3 AND D.amount = 20)
GROUP BY P.id
HAVING count(P.id) = 3
答案 2 :(得分:1)
我最终得到了
SELECT * FROM table WHERE ProductID IN
(SELECT ProductId
FROM table
WHERE (qty = X AND price = X) OR (qty = X AND price = X) OR (qty = X AND price = X)
GROUP BY ProductID
HAVING COUNT(ProductID) = 3)
GROUP BY productID
ORDER BY productID, qty
这给了我所需的过滤功能。谢谢你让我开始!