-1

I have the following table schema:

Table 1
-
field1
Table 2
-
field1 | field2

What I want to do is select field2 from the second table where field1 in the second table doesn't exist in the first table (field1).

I had this :

SELECT t2.field2
     , t2.field1
FROM table1 t1
   , table2 t2
WHERE t2.field1 != t1.field1

The problem is that this query will retrieve multiple repeated information from table2 if multiple rows apply in table1. I added DISTINCT and/or LIMIT but it still doesn't work. Any idea on how to do this?

4

3 回答 3

3

您可以使用子查询:

SELECT t2.field2, t2.field1 FROM table2 t2 WHERE t2.field1 NOT IN (SELECT t1.field1 FROM table1 t1);

这将为您提供所有行table2中的 a field1which is not in table1

您现在可以在最外层查询上使用DISTINCT或进行任何进一步的处理。LIMIT

于 2015-01-24T23:21:25.640 回答
2

您问题的标题几乎就是您需要的命令:'NOT EXIST'。SQL 就是这么简单。;)

SELECT DISTINCT t2.field2 
FROM Table2 t2
WHERE NOT EXISTS (SELECT * FROM Table1 WHERE t1.field1 = t2.field1)
于 2015-01-24T23:21:37.460 回答
2

您可以LEFT JOIN与 check 一起使用IS NULL

SELECT DISTINCT t2.field2
FROM table2 t2
LEFT JOIN table1 t1 ON t1.field1 = t2.field1
WHERE t1.field1 IS NULL
于 2015-01-24T23:20:52.573 回答