我在具有两列主键的特定表中遇到GROUP BY查询问题。
我的表看起来像这样:
CREATE TABLE IF NOT EXISTS `stocks` (
`id_city` int(10) NOT NULL,
`id_prod` int(10) NOT NULL,
`sell_price` int(10) DEFAULT '0',
PRIMARY KEY (`id_city`,`id_prod`)
)
假设它插入了这样的值:
INSERT INTO `stocks` (`id_city`, `id_prod`, `sell_price`)
VALUES ('1', '1', '100'), ('2', '1', '90'), ('3', '1', '10');
经过这样的查询:
SELECT id_prod, id_city, MIN(sell_price)
FROM stocks
GROUP BY id_prod
结果行丢失'id_city'键 - 它首次出现在city_id上,
id_prod id_city MIN(sell_price)
1 1 10
如何为此案例构建正确的查询?结果应如下所示:
id_prod id_city MIN(sell_price)
1 3 10
答案 0 :(得分:2)
如果要返回包含min(sell_price)
的记录,可以使用子查询:
SELECT s1.id_prod,
s1.id_city,
s1.sell_price
FROM stocks s1
inner join
(
select id_prod, MIN(sell_price) sell_price
from stocks
group by id_prod
) s2
on s1.id_prod = s2.id_prod
and s1.sell_price = s2.sell_price
返回:
| ID_PROD | ID_CITY | SELL_PRICE |
----------------------------------
| 1 | 3 | 10 |
答案 1 :(得分:1)
你的意思是使用max(id_city)
SELECT id_prod, max(id_city) city , MIN(sell_price)
FROM stocks
GROUP BY id_prod
或类似使用count(id_city)
SELECT id_prod, count(id_city) city, MIN(sell_price)
FROM stocks
GROUP BY id_prod
都返回
ID_PROD CITY MIN(SELL_PRICE)
1 3 10
修改强>
通过INNER JOIN
SELECT s.id_prod,
s.id_city,
s.sell_price
FROM stocks s
inner join
(
select id_prod, MIN(sell_price) sell_price
from stocks
group by id_prod
) s1
on s.id_prod = s1.id_prod
and s.sell_price = s1.sell_price
答案 2 :(得分:0)
您还必须将id_city
添加到GROUP BY
子句中