我正在用这个查询连接 3 个表
SELECT DISTINCT a.number, c.quantity, c.retail_price
FROM catalog.product `a`
JOIN catalog.product_variation `b` ON a.id = b.product_id
JOIN catalog.price_regular `c` ON b.id = c.product_variation_id
WHERE c.retail_price BETWEEN 5 AND 6 AND a.status_id = 1
ORDER BY a.number, c.retail_price DESC
我得到了这个结果集
number|quantity|retail_price
---------------------
1007 | 288 | 5.750
1007 | 48 | 5.510
1007 | 576 | 5.460
1007 | 96 | 5.240
1007 | 576 | 5.230
1007 | 144 | 5.120
1006 | 200 | 5.760
1006 | 100 | 5.550
1006 | 200 | 5.040
1006 | 500 | 5.010
我需要的结果是仅包含 quantity
列中具有最大值的行以及具有最大 retail_price
的行。所以我需要的结果集看起来像这样
number|quantity|retail_price
---------------------
1006 | 500 | 5.010
1007 | 576 | 5.460
我在 SO 上找到了一些帖子,但没有一个对连接多个表有帮助。我需要一个sql语句来获取上面指定的结果集
最佳答案
这是一个简单的 GROUP BY 查询
SELECT a.number, max(c.quantity) as qty, max(c.retail_price) as price
FROM catalog.product `a`
JOIN catalog.product_variation `b` ON a.id = b.product_id
JOIN catalog.price_regular `c` ON b.id = c.product_variation_id
WHERE c.retail_price BETWEEN 5 AND 6
AND a.status_id = 1
GROUP BY a.number;
关于mysql - 复合 Mysql join sql 中每组所需的最大 n,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29080006/