首页 文章

MySQL在子查询结果周围加入

提问于
浏览
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

有没有办法做一次子查询得到 product_bids 的PK,并加入(子查询的结果)或任何干净的方式这样做?

附注:无论如何,查询优化器是否会认识到这一点,使其变得不那么重要了?

谢谢

2 回答

  • 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需要相当于一个记录所具有的值,否则您将乘以您不想要的行 . 如果不是这种情况(这意味着您不能依赖一个作为顶部),您的提案也会遇到类似问题,因为您尚未定义具有最大日期的记录 .

  • 0

    您可以将表格与子查询一起加入,该子查询为每种产品选择最新的出价日期:

    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
    

相关问题