2

我有以下脚本,它显示了 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 条记录)。

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

4

2 回答 2

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
于 2013-02-19T14:24:58.683 回答
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 |
+------+
于 2013-02-19T14:25:10.230 回答