[英]MySQL selecting rows that are not in grouping
我有以下示例數據的MySQL表:
create table prices (
id INTEGER PRIMARY KEY AUTO_INCREMENT,
store_id INTEGER NOT NULL,
item INTEGER NOT NULL,
price FLOAT NOT NULL
);
insert into prices values(1,1,1,1.25);
insert into prices values(2,1,2,.99);
insert into prices values(3,2,2,1.20);
insert into prices values(4,3,3,3.25);
insert into prices values(5,3,1,1.35);
我正在尋找一個查詢來選擇公司不會用於購買產品的任何store_id
。 例如,在prices
,將不使用store_id
2,因為可以從store_id
1中便宜地購買item
2。
我將如何處理? 謝謝。
使用此查詢:
select item, min(price) minprice
from prices
group by item
您將獲得每件商品的最低價格。
如果您將表prices
left join
上面的查詢中,並且僅保留不匹配的行(意味着該商品的價格沒有最便宜的行),那么您將獲得所有可以找到的更便宜的商店和商品:
select p.*
from prices p left join (
select item, min(price) minprice
from prices
group by item
) g on g.item = p.item and g.minprice = p.price
where g.item is null
參見演示 。
結果:
| id | store_id | item | price |
| --- | -------- | ---- | ----- |
| 3 | 2 | 2 | 1.2 |
| 5 | 3 | 1 | 1.35 |
如果您只想要不從以下商店購買任何東西的商店:
select p.store_id
from prices p left join (
select item, min(price) minprice
from prices
group by item
) g on g.item = p.item and g.minprice = p.price
group by p.store_id
having sum(g.item is not null) = 0
參見演示 。
結果:
| store_id |
| -------- |
| 2 |
SELECT *, MIN(price) from prices group by item
給您具有最便宜商品的store_id 。
輸出示例:
id | store_id | 項目| 價格| MIN(價格)
1 | 1 | 1 | 1.25 | 1.25
2 | 1 | 2 | 0.99 | 0.99
4 | 3 | 3 | 3.25 | 3.25
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.