MySQL获取每个产品组的列值最小的行[重复]
Posted
技术标签:
【中文标题】MySQL获取每个产品组的列值最小的行[重复]【英文标题】:MySQL get the row with smallest column value for each product group [duplicate] 【发布时间】:2019-11-20 08:22:27 【问题描述】:我有表 products
和 product_prices
。就这样;
products:
+-------------+----------+
| products_id | title |
+-------------+----------+
| 1 | phone |
| 2 | computer |
| 3 | keyboard |
+-------------+----------+
product_prices:
+-------------------+-----------+-------+-------------+
| product_prices_id | productid | price | minquantity |
+-------------------+-----------+-------+-------------+
| 1 | 1 | 500 | 1 |
| 2 | 1 | 450 | 2 |
| 3 | 2 | 800 | 1 |
| 4 | 2 | 700 | 2 |
| 5 | 3 | 15 | 1 |
| 6 | 3 | 10 | 3 |
| 7 | 3 | 7 | 10 |
+-------------------+-----------+-------+-------------+
因此根据数量有多种价格。 我的 SQL 查询是这样的:
SELECT
*
FROM
products product
INNER JOIN
product_prices price
ON price.productid = product.products_id
GROUP BY
product.products_id
ORDER BY
price.price;
我收到此错误:
Expression #3 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'price.product_prices_id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by
没有 GROUP BY 的结果是:
+-------------+----------+-------------------+-----------+-------+-------------+
| products_id | title | product_prices_id | productid | price | minquantity |
+-------------+----------+-------------------+-----------+-------+-------------+
| 3 | keyboard | 7 | 3 | 7 | 10 |
| 3 | keyboard | 6 | 3 | 10 | 3 |
| 3 | keyboard | 5 | 3 | 15 | 1 |
| 1 | phone | 2 | 1 | 450 | 2 |
| 1 | phone | 1 | 1 | 500 | 1 |
| 2 | computer | 4 | 2 | 700 | 2 |
| 2 | computer | 3 | 2 | 800 | 1 |
+-------------+----------+-------------------+-----------+-------+-------------+
我要做的是,获取价格最便宜的行,按products_id分组;
+-------------+----------+-------------------+-----------+-------+-------------+
| products_id | title | product_prices_id | productid | price | minquantity |
+-------------+----------+-------------------+-----------+-------+-------------+
| 3 | keyboard | 7 | 3 | 7 | 10 |
| 1 | phone | 2 | 1 | 450 | 2 |
| 2 | computer | 4 | 2 | 700 | 2 |
+-------------+----------+-------------------+-----------+-------+-------------+
我想我需要使用 MIN() 但我尝试了几件事,但没有奏效。我能做的最接近的是按价格订购,限制为 1 个,但它只返回 1 个产品。 有什么想法吗?
如果有帮助,这里是我使用的示例数据库的转储:https://transfer.sh/dTvY4/test.sql
【问题讨论】:
【参考方案1】:您首先需要了解每种产品的最低价格是多少。为此,您使用 MIN
-aggregate 函数。当您选择具有聚合函数的普通列时,您需要在GROUP BY
-clause 中列出普通列。
一旦您知道每种产品的最低价格,您只需从两个表的连接中选择这些行:
select
p.products_id,
p.title,
pr.product_prices_id,
pr.productid,
pr.price,
pr.minquantity
from product_prices pr
join products p on p.products_id=pr.productid
join (
select productid, min(price) as minprice
from product_prices
group by productid
) mpr on mpr.productid=pr.productid and mpr.minprice=pr.price
见SQLFiddle。
在您的查询中,您尝试使用 GROUP BY
-clause 而不使用聚合函数,因此会出现错误。此外,您缺少 MIN 逻辑。
与其将文件链接到问题,不如为它创建一个 SQLFiddle / db-fiddle。这样就更容易回答问题了。
【讨论】:
以上是关于MySQL获取每个产品组的列值最小的行[重复]的主要内容,如果未能解决你的问题,请参考以下文章