Sql Query for Identified by duplicates并在其中删除

时间:2018-04-20 06:45:24

标签: sql

SELECT i.product_id, o.date_added 
FROM ims_order_product i 
   INNER JOIN ims_order o 
WHERE  i.product_id IN (SELECT p.product_Id FROM ims_product p)

Query Return Product_id列和Date列但是Product_id列包含重复项所以我想根据最近日期的Date_added删除Product_id中的重复项。任何人都可以给出答案。

3 个答案:

答案 0 :(得分:0)

尝试按product_id分组。以下查询将选择重复product_id的最新日期

SELECT i.product_id, MAX(o.date_added) FROM ims_order_product i INNER JOIN ims_order o WHERE i.product_id IN (SELECT p.product_Id FROM ims_product p) GROUP BY i.product_id

答案 1 :(得分:0)

请尝试此查询

SELECT i.product_id, MAX(o.date_added) date_added
FROM ims_order_product i 
INNER JOIN ims_order o --add your join condition here
WHERE EXISTS (SELECT p.product_Id FROM ims_product p WHERE p.product_Id = i.product_id)
GROUP BY i.product_id

答案 2 :(得分:0)

SELECT * FROM(SELECT i.product_id,o.date_added,o.order_id FROM ims_order_product i JOIN ims_order o ON o.order_id = i.order_id JOIN ims_product pr ON pr.product_id = i.product_id ORDER BY date_added DESC)AS sub GROUP BY product_id