如果一列不为null,如何排除具有相同id的所有行

时间:2016-03-01 10:48:30

标签: mysql sql

我的以下查询:

select oh.id_order,pc.id_product_comment,od.product_id
from `ps_order_history` oh
INNER JOIN `ps_orders` o ON o.id_order = oh.id_order
INNER JOIN `ps_order_detail` od ON od.id_order = oh.id_order
LEFT JOIN `ps_product_comment` pc ON pc.`id_customer` = o.`id_customer` AND pc.`id_product` = od.`product_id`
where oh.`id_order_state` = 2
AND (oh.date_add < pc.date_add OR pc.date_add IS NULL)

返回以下结果:

id_order  |  id_product_comment  |  product_id
----------------------------------------------
  6              3                 6
  6             NULL               5
  5             NULL               6
  5             NULL               5

我想排除id_order 6的行,因为一行的id_product_comment不为null。 有什么想法吗?

2 个答案:

答案 0 :(得分:0)

好的解决方案:

    select oh.id_order,pc.id_product_comment,od.product_id
from `ps_order_history` oh
INNER JOIN `ps_orders` o ON o.id_order = oh.id_order
INNER JOIN `ps_order_detail` od ON od.id_order = oh.id_order
LEFT JOIN `ps_product_comment` pc ON pc.`id_customer` = o.`id_customer` AND pc.`id_product` = od.`product_id`
where oh.`id_order_state` = 2
AND (oh.date_add < pc.date_add OR pc.date_add IS NULL)
GROUP BY oh.id_order
HAVING pc.id_product_comment IS NULL

答案 1 :(得分:0)

使用子查询的解决方案。子查询获取id_order的列表,其中包含ps_product_comment上的任何条目。这将继续连接到主查询,然后WHERE子句检查没有匹配的记录。

SELECT oh.id_order,
        pc.id_product_comment,
        od.product_id
FROM `ps_order_history` oh
INNER JOIN `ps_orders` o ON o.id_order = oh.id_order
INNER JOIN `ps_order_detail` od ON od.id_order = oh.id_order
LEFT OUTER JOIN `ps_product_comment` pc ON pc.`id_customer` = o.`id_customer` AND pc.`id_product` = od.`product_id`
LEFT OUTER JOIN
(
    SELECT o.id_order
    FROM ps_orders` o 
    INNER JOIN `ps_order_detail` od ON od.id_order = o.id_order
    INNER JOIN `ps_product_comment` pc ON pc.`id_customer` = o.`id_customer` AND pc.`id_product` = od.`product_id`
) sub0
ON sub0.id_order = oh.id_order
WHERE oh.`id_order_state` = 2
AND (oh.date_add < pc.date_add 
OR pc.date_add IS NULL)
AND sub0.id_order IS NULL