【发布时间】: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
【问题讨论】:
标签: mysql sql group-by aggregate-functions greatest-n-per-group