0

我需要查询我的数据库,其中一个表的唯一字段存在于另一个表中,并且使用它我只需要获取第二个表中在表行中没有匹配字段的记录以获取表一中的记录。

4

2 回答 2

1
SELECT * FROM SECOND TABLE WHERE COLUMN_ID NOT IN(SELECT COLUMN_ID FROM FIRST TABLE);

阅读更多关于 NOT IN 的信息:

http://www.w3schools.com/sql/sql_in.asp

于 2013-05-25T11:41:59.227 回答
0

试试这个:
查找一个表中不存在于另一个表中的记录或 NOT IN、LEFT JOIN 和 NOT EXISTS 之间的差异。

    SELECT a.i
FROM tableA   AS a
WHERE a.i NOT IN (SELECT b.j FROM tableB   AS b) OR a.i IS NULL
 ----------OR   There are at least three other ways to do this, which all are much more efficient!
    SELECT a.i FROM tableA AS a
        WHERE a.i NOT IN (SELECT b.j FROM tableB  AS b)
        UNION ALL
        SELECT a.i
        FROM tableA  AS a
        WHERE a.i IS NULL
     ----------OR   
        SELECT a.i
        FROM tableA  AS a
        LEFT JOIN tableB   AS b ON b.j = a.i
        WHERE b.j IS NULL
    ----------OR     
        SELECT a.i
        FROM tableA  AS a
        WHERE NOT EXISTS (SELECT * FROM tableB   AS b WHERE b.j = a.i)
于 2014-01-29T13:58:05.110 回答