我创建了以下表格:
create table items (
id serial primary key,
store_id int,
);
create table bids (
item_id int,
amount int
);
我想从特定商店中选择所有商品,并包含有关最高出价的信息:
select items.*, max(bids.amount) from items
join bids on bids.item_id = items.id
where items.store_id = $store_id
我收到以下错误:
列“items.id”必须出现在GROUP BY子句中或用于聚合函数
我做错了什么?
答案 0 :(得分:1)
也许你想要一个窗口功能?
select items.*,
max(bids.amount) over (partition by bids.item_id) as max_bid_for_item
from items
join bids on bids.item_id = items.id
where items.store_id = $store_id
答案 1 :(得分:0)
您的错误消息会告诉您出错了什么。要使用聚合函数(max()
),SELECT
子句中的所有其他内容都必须位于GROUP BY
子句中。
SELECT items.*, MAX(bids.amount)
FROM items
JOIN bids ON bids.item_id = items.id
WHERE items.store_id = $store_id
GROUP BY items.id,items.store_id;
答案 2 :(得分:0)
SELECT *
FROM items i
JOIN bids b ON b.item_id = i.id
WHERE i.store_id = $store_id
AND NOT EXISTS (
SELECT *
FROM bids nx -- No bid should exist
WHERE nx.item_id = b.item_id -- ... for the same item
AND nx.amount > b.amount -- ... but with a higher price
);