MySQL LEFT JOIN, GROUP BY and ORDER BY not working as required

前端 未结 4 1840
清歌不尽
清歌不尽 2020-12-16 17:18

I have a table

\'products\' => (\'product_id\', \'name\', \'description\') 

and a table

\'product_price\' => (\'pro         


        
4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-16 17:39

    Mysqlism:

    SELECT p.*, MAX(pp.date_updated), pp.price 
    FROM products p 
    LEFT JOIN product_price pp ON pp.product_id = p.product_id
    GROUP BY p.product_id 
    

    Will work on some RDBMS:

    SELECT p.*, pp.date_updated, pp.price 
    FROM products p 
    LEFT JOIN product_price pp ON pp.product_id = p.product_id
    WHERE (p.product_id, pp.date_updated) 
    
       in (select product_id, max(date_updated) 
           from product_price 
           group by product_id)
    

    Will work on most RDBMS:

    SELECT p.*, pp.date_updated, pp.price 
    FROM products p 
    LEFT JOIN product_price pp ON pp.product_id = p.product_id
    
    WHERE EXISTS
    (
        select null -- inspired by Linq-to-SQL style :-)
        from product_price 
    
        WHERE product_id = p.product_id 
    
        group by product_id
    
        HAVING max(date_updated) = pp.date_updated
    )
    

    Will work on all RDBMS:

    SELECT p.*, pp.date_updated, pp.price 
    FROM products p 
    LEFT JOIN product_price pp ON pp.product_id = p.product_id
    
    LEFT JOIN 
    (
        select product_id, max(date_updated) as recent 
        from product_price 
        group by product_id
    ) AS latest 
    ON latest.product_id = p.product_id AND latest.recent = pp.date_updated
    

    And if nate c's code intent is to just get one row from product_price, no need to table-derive (i.e. join (select product_price_id, max(date_updated) from products_price) as pp_max), he might as well just simplify(i.e. no need to use the product_price_id surrogate primary key) it like the following:

    SELECT p.*, pp.date_updated, pp.price 
    FROM products p 
    LEFT JOIN product_price pp ON pp.product_id = p.product_id
    WHERE pp.date_updated = (select max(date_updated) from product_price)
    

提交回复
热议问题