我有三张这样的表
orders(id, status, ...)
products(id, created_at, ...)
product_order(order_id, product_id, quantity)
我想先选择售出最多的产品,然后继续考虑最新产品数量,这是我的尝试
SELECT products.* FROM products
LEFT JOIN product_order ON product_order.product_id = products.id
LEFT JOIN orders ON orders.id = product_order.order_id
WHERE orders.status != 'REJECTED'
GROUP BY product_order.product_id
ORDER BY COUNT(*) DESC, products.created_at
此声明返回未首先销售的产品,因为我使用的是左连接,并且它们的数量超过了已售出的产品..我也不知道如何考虑数量
谢谢,
答案 0 :(得分:2)
这应该有效:
SELECT p.*, sum(po.quantity) qty
FROM products p
LEFT OUTER JOIN product_order po ON po.product_id = p.id
LEFT OUTER JOIN orders o ON o.id = po.order_id
WHERE o.status != 'REJECTED'
GROUP BY po.product_id
ORDER BY qty DESC, p.created_at
答案 1 :(得分:0)
如果您想要销售最多的产品,可以添加
AND products.quantity = SELECT max(quantity) from products
在您的WHERE
声明后