SQL连接排除结果

时间:2014-03-05 15:12:09

标签: sql join where

这可能很容易,但我现在无法弄明白。

表顺序

+----+---------+
| id |  name   |
+----+---------+
| 1  | Order 1 |
| 2  | Order 2 |
| 3  | Order 3 |
+----+---------+

表Facturationdetails

+----+----------------+
| id |      name      |
+----+----------------+
| 1  | Transportation |
| 2  | Regular        |
| 3  | Fixed          |
+----+----------------+

表关系:

表Facturationdetails

+----------+---------+
| order_id | fact_id |
+----------+---------+
| 1        | 1       |
| 1        | 2       |
| 1        | 3       |
| 2        | 2       |
| 2        | 3       |
| 3        | 2       |
+----------+---------+

现在我想知道哪个订单没有fakturationdetails1(运输)

select to.order_id
from table_order to
join table_facturation tf
on tf.order_id = to.order_id
where tf.fakt_id != 1

但这将返回所有行:

+---+---+
| 1 | 2 |
| 1 | 3 |
| 2 | 2 |
| 2 | 3 |
| 3 | 2 |
+---+---+

我希望结果如下:

订单2和订单3.

2 个答案:

答案 0 :(得分:1)

我怀疑您要使用NOT EXISTS,因此,不要找到fact_id不是1的行,而是从表格中找到其中fact_id 1的订单,然后排除这些订单:

SELECT  o.order_id
FROM    table_order o
WHERE   NOT EXISTS
        (   SELECT  1
            FROM    table_facturation tf
            WHERE   tf.order_id = o.order_id
            AND     tf.fakt_id = 1
        );

您尚未指定DBMS,但如果您使用LEFT JOIN\IS NULL使用MySQL you will get better performance

SELECT  o.order_id
FROM    table_order o
        LEFT JOIN table_facturation tf
            ON tf.order_id = o.order_id
            AND tf.fakt_id = 1
WHERE   tf.order_id IS NULL;

答案 1 :(得分:0)

解决此问题的一种方法是使用left join并在where子句中进行比较。寻找匹配的东西,然后选择那些没有匹配的东西:

select to.order_id
from table_order to left join
     table_facturation tf
     on tf.order_id = to.order_id and
        tf.fakt_id = 1
where tf.fakt_id is null;