SQL:选择第二个表中不存在的类似行和行

时间:2015-02-04 15:28:24

标签: mysql sql

TABLE1:

+-----------+----------+
|    CODE   |  TYPEID  |
+-----------+----------+
| 441       |  mn014   |
| 223       |  mn014   |
| 224       |  mn014   |
| 655       |  mn089   |
| 854       |  mn089   |
| 449       |  mn032   |
+-----------+----------+

TABLE2:

+-----------+----------+----------+
| CODE      | TAKENDTE | RTURNDTE |
+-----------+----------+----------+
| 441       | 25/08/14 | 01/01/15 |
| 223       | 25/08/14 | 03/01/15 |
| 223       | 25/08/14 | 01/02/15 |
| 223       | 25/08/14 |   NULL   |
| 655       | 25/08/14 | 07/01/15 |
| 854       | 25/08/14 |   NULL   |
| 449       | 25/08/14 | 06/01/15 |
+-----------+---------------------+

我想选择第二个表中不存在的typeid mn014的所有代码,或者在表2中存在的所有实例中的RTURNDTE列中都不为NULL

我在想这样的事情:

SELECT DISTINCT T1.CODE
FROM TABLE1 T1 LEFT JOIN TABLE2 T2

ON T1.CODE=T2.CODE
WHERE TYPEID='mn014' AND (RTURNDTE IS NOT NULL OR T2.CODE IS NULL)

那没用,有什么想法吗?

2 个答案:

答案 0 :(得分:2)

您可以将其标记为NOT EXISTS - 并在table2上添加过滤器。您正在寻找表1中没有记录的记录,其中NULL返回日期(如果我理解正确的话)。

select t1.*
from table1 t1
where typeid = 'mn014' and
      not exists (select 1
                  from table2 t2
                  where t2.code = t.code and
                        t2.rturndte is null
                 );

答案 1 :(得分:0)

试试这个:

SELECT t1.*
FROM table1 t1
WHERE NOT EXISTS(
    SELECT 'CODE'
    FROM table2 t2
    WHERE t1.code = t2.code
)
OR 
NOT EXISTS(
    SELECT 'NULLABLE'
    FROM table2 t2
    WHERE t2.code = t1.code
    AND t2.RTURNDTE IS NULL
)
AND t1.typeid = 'mn014'