当我使用以下 sql 运行查询时
SELECT
userproduct_id,product_id,offer_price
FROM `tbluserproducts`
WHERE `product_id` = '4722'
ORDER BY `offer_price` asc
它显示这样的结果
userproduct_id product_id offer_price
4848 4722 1200
4835 4722 12500
4837 4722 12500
4841 4722 17000
当在上面的sql中添加groupby Product_id时
SELECT
userproduct_id,product_id,offer_price
FROM `tbluserproducts`
WHERE `product_id` = '4722'
group by product_id
ORDER BY `offer_price` asc
只显示一条记录
userproduct_id product_id offer_price
4835 4722 12500
但它不显示 userproduct_id 4848
记录,因为我按报价升序
订购
我的表格结构如下
Column Type
userproduct_id int(10) unsigned Auto Increment
product_id int(11) unsigned
offer_price decimal(30,0)
最佳答案
当您使用 GROUP BY 时,查询会返回 Product_id 4722 的一行。如果组中有多行,MySQL 会从该组行中选择一行。
它如何选择行?
它必须按某种顺序读取行,并且它选择读取的第一行。它在此查询中按 PRIMARY KEY 顺序读取行,因此显示 userproduct_id
最少的行。
您给出的ORDER BY
在之后应用GROUP BY
将输出减少到一行,因此它对一组一行进行排序,但这没有任何效果。
我认为您想返回 offer_price
最少的行,对吧?您可以在问题中更清楚地表达这一点。
这基本上与 Stack Overflow 上被问过数百次的问题类型相同。标签greatest-n-per-group用于解决这种一般类型的问题。
在您的查询中,您仅选择一个product_id,因此可以轻松使用 LIMIT 仅返回第一行。
SELECT
userproduct_id, product_id, offer_price
FROM `tbluserproducts`
WHERE `product_id` = '4722'
ORDER BY `offer_price` asc
LIMIT 1
如果您想要多个product_id,并且每个产品都有最低offer_price
的行,则情况会稍微复杂一些。在MySQL 8.0中,您可以使用窗口函数:
WITH ranked_userproducts AS (
SELECT
userproduct_id, product_id, offer_price,
ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY offer_price) AS rownum
FROM `tbluserproducts`
)
SELECT
userproduct_id, product_id, offer_price
FROM ranked_userproducts
WHERE rownum = 1;
在MySQL 5.x中,您可以尝试另一种方法:
SELECT
userproduct_id, product_id, offer_price
FROM `tbluserproducts` AS p1
JOIN (
SELECT product_id, MIN(offer_price) AS offer_price
GROUP BY product_id ORDER BY NULL
) AS p2
ON p1.product_id = p2.product_id AND p1.offer_price = p2.offer_price;
可能还有其他解决方案。我建议您关注greatest-n-per-group标记并阅读其他一些答案。
关于mysql - Group By mysql在排序时显示不同的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54069823/