鍍金池/ 問答/數(shù)據(jù)庫/ 請教這個(gè)sql怎么寫?

請教這個(gè)sql怎么寫?

現(xiàn)在商品item表結(jié)構(gòu)
item_id, title, product_id, type, price

一個(gè)product下有多個(gè)商品,商品item有4種type(0,1,2,3),同一個(gè)type下可以有多個(gè)同樣type與同樣product_id的商品。

現(xiàn)在有N個(gè)商品id,我要根據(jù)這些商品id,來獲取這些商品的product_id,然后根據(jù)這些product_id再獲取item表里面,所有 product_id與4個(gè)type值組合下的一個(gè)price最低的商品 的列表。

應(yīng)該怎么寫sql?

回答
編輯回答
憶往昔
select aa.* 
from item aa 
join (
    select a.product_id,a.type,min(a.price) price 
    from item a 
    join (select product_id from item where item_id in (N) ) b
    on a.product_id=b.product_id
    group by product_id,type) bb
on aa.product_id=bb.product_id and aa.type=bb.type and aa.price=bb.price;
2017年1月15日 13:16