0

我创建了以下表格:

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 子句中或在聚合函数中使用

我究竟做错了什么?

4

3 回答 3

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
于 2013-06-30T21:36:39.170 回答
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;
于 2013-06-30T18:49:00.960 回答
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
   );
于 2013-06-30T19:01:57.970 回答