0

我有这个查询(请注意,所有 3 个子查询都从同一行中选择不同的列)。本质上,我想在行product_bid旁边获得最大日期的product行。

SELECT 
p.product_id,
p.product_title, 
(SELECT b.bid_id FROM product_bids b WHERE b.bid_product_id=p.product_id ORDER BY b.bid_date DESC LIMIT 1) AS bid_id,
(SELECT b.bid_date FROM product_bids b WHERE b.bid_product_id=p.product_id ORDER BY b.bid_date DESC LIMIT 1) AS bid_date,
(SELECT b.bid_amount FROM product_bids b WHERE b.bid_product_id=p.product_id ORDER BY b.bid_date DESC LIMIT 1) AS bid_amount

FROM product p

WHERE p.product_auction_id=325

有没有办法做一次子查询以获得 PKproduct_bids并加入它(子查询的结果)或任何干净的方式来做到这一点?

旁注:查询优化器是否会认识到这一点,使其不那么重要?

谢谢

4

2 回答 2

1

您可以将表与为每个产品选择最新投标日期的子查询连接在一起:

SELECT p.product_id, b.bid_id, b.bid_date, b.bid_amount
FROM   product_bids AS b NATURAL JOIN (
         SELECT   bid_product_id, MAX(bid_date) AS bid_date
         FROM     product_bids
         GROUP BY bid_product_id
       ) AS t
  JOIN product AS p ON p.product_id = b.bid_product_id
WHERE  p.product_auction_id = 325
于 2012-05-31T10:17:38.617 回答
0

在一个 SQL 查询中执行此操作可能很困难,但我有这个建议。首先从 product_bids 中选择最大日期,然后进行第二次查询,如下所示:

select p.product_id, p.product_title, b.bid_id, b.bid_date, b.bid_amount
from product p
inner join product_bids b on b.bid_date = @yourselectedbiddate

这应该获取完全相同的数据,但性能要高得多。请注意,@yourselectedbiddate 需要等于一个记录恰好具有的值,否则您将乘以您不想要的行。如果不是这种情况(这意味着您不能依赖一个是顶部),您的提案也会遇到类似的问题,因为您尚未定义具有最大日期的记录中的哪一个在前。

于 2012-05-31T10:16:47.617 回答