MySQL反向匹配

时间:2013-02-19 14:21:50

标签: mysql

我有以下脚本,它显示了ADATA表和CDATA表中的记录数据,并用名字和姓氏(我在两个表中只有两个相同的字段)匹配:

SELECT
c.asdf AS ASDF,
CONCAT(a.genr, ' ' ,a.firstname, ' ' ,a.lastname) AS Name,
a.rcvdate AS Report_Date,
c.enroll AS Enroll_Date,
a.cvb AS CVB,
c.pctcomp AS Percent_Complete

FROM
adata a,
cdatas c

WHERE
a.firstname = c.firstname
AND a.lastname = c.lastname

我需要做的是获取ADATA中但不在CDATA中的记录列表,以及CDATA中不在ADATA中的记录。我在脚本的WHERE部分尝试了使用NOT的所有不同变体,但总是给我800 - ADATA中的记录总数(CDATA表只有130条记录)。

有没有办法正确地做到这一点?

2 个答案:

答案 0 :(得分:2)

SELECT columns
FROM
    adata a
    LEFT JOIN cdatas c ON (a.firstname = c.firstname AND a.lastname = c.lastname)
WHERE
    c.asdf IS NULL
UNION ALL
SELECT columns
FROM
    cdatas c
    LEFT JOIN adata a ON (c.firstname = a.firstname AND c.lastname = a.lastname)
WHERE
    a.cvb IS NULL

答案 1 :(得分:1)

mysql> create table a (x int);
mysql> create table b (y int);
mysql> insert into a values (1), (2), (3), (4), (5);
mysql> insert into b values (2), (4), (6);
mysql> select x from a where not x in (select y from b);
+------+
| x    |
+------+
|    1 |
|    3 |
|    5 |
+------+
mysql> select y from b where not y in (select x from a);
+------+
| y    |
+------+
|    6 |
+------+