SELECT ai.auction_item_id, ai.starting_bid, b.bid_amount, i.*
FROM
auction_item as ai, //Table contains auction specific details about the item
item as i //Table contains general details about the item
INNER JOIN (
SELECT auction_item_id, bid_amount
FROM bid xb //Table contains bids on item
ORDER BY amount DESC
LIMIT 1 ) b
ON b.auction_item_id = ai.auction_item_id
WHERE
ai.auction_id = 4 AND
i.id = ai.listings_id
ORDER BY RAND()
LIMIT 4
目前通过上述查询,我可以从当前有效拍卖中获得4个随机项目(拍卖#4)。但他们目前都以相同的最高出价金额回归(来自内部联盟)。每个项目都应有自己的最高出价金额(来自内部联接) - 除非该项目没有出价,那么它应为0(或某事)
我在这里做错了什么? 对于每个出价,出价表都有一行,因此LIMIT 1和内部联接中的desc按顺序排序,因为我想要对外部区域中的每个项目进行最高出价。 (如果有出价)。
由于
答案 0 :(得分:2)
尝试子查询。如果由于0
而在出价表中没有条目,则会获得coalesce
。
SELECT
ai.auction_item_id, ai.starting_bid,
Coalesce((SELECT max(xb.bid_amount)
FROM bid xb
WHERE xb.auction_item_id = ai.auction_item_id), 0) AS bid_amount,
i.*
FROM auction_item AS ai
INNER JOIN item AS i ON i.id = ai.listings_id
WHERE ai.auction_id = 4
ORDER BY Rand()
答案 1 :(得分:1)
这样的东西?
SELECT ai.auction_item_id, ai.starting_bid, b.bid_amount, max(bid_amount)
FROM auction_item as ai
inner join bid b
on ai.auction_item_id = b.auction_item_id
inner join items i
on i.id = ai.listings_id
where ai.auction_id = 4
将表格架构添加到问题中会有所帮助
修改强>:
SELECT ai.auction_item_id, ai.starting_bid, IFNULL(max(bid_amount), 0) max_bid
FROM auction_item as ai
left join bid b
on ai.auction_item_id = b.auction_item_id
inner join items i
on i.id = ai.listings_id
WHERE ai.auction_id = 4
GROUP BY ai.auction_item_id
在这里,包括没有出价项目。
如果我有错误的话,请告诉我:http://sqlfiddle.com/#!9/0eae7/2
答案 2 :(得分:1)
有几个问题:
LIMIT 1
交叉加入派生表只会重复每次最高出价,更糟糕的是,它不会被过滤,因此它将是 any <的最高出价/ em>拍卖,如果该行不适用于当前auction_item_id
,则会将其加入。将LIMIT移动到外部查询。LEFT JOIN
返回一行。INNER JOIN
auction_item
到item
(您的初始查询无法运行)修改强>
道歉,最初,我不明白你想要实现的目标。如果您想要任何4个随机auction_items
的最高出价(如果没有出价则为0),这里有一种方法可以使用2个派生表:
auction_items
LEFT JOIN
两个派生表一起
SELECT items.auction_item_id, IFNULL(topBids.amount, 0) as topBid
FROM
(SELECT auction_item_id
FROM auction_item
ORDER BY RAND()
LIMIT 4
) items
LEFT JOIN
(SELECT b.auction_item_id, b.amount
FROM bid b
GROUP BY b.auction_item_id
ORDER BY amount DESC) topBids
ON items.auction_item_id = topBids.auction_item_id;