首页 文章

SELECT字段,其他表中没有其他字段

提问于
浏览
-1

我有以下表架构:

Table 1
-
field1
Table 2
-
field1 | field2

我想要做的是选择 field2 from the second table ,其中第二个表中的 field1 在第一个表( field1 )中不存在 .

我有这个:

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

问题是如果table1中有多行适用,此查询将从table2检索多个重复信息 . 我添加了 DISTINCT 和/或 LIMIT 但它仍然不起作用 . 有关如何做到这一点的任何想法?

3 回答

  • 3

    您可以使用子查询:

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

    这将为您提供 table2field1 不在 table1 中的所有行 .

    您现在可以在最外层查询上使用 DISTINCTLIMIT 进行任何进一步处理 .

  • 2

    您可以将 LEFT JOINIS NULL 一起使用检查:

    SELECT DISTINCT t2.field2
    FROM table2 t2
    LEFT JOIN table1 t1 ON t1.field1 = t2.field1
    WHERE t1.field1 IS NULL
    
  • 2

    你问题的 Headers 几乎就是你需要的命令:'不存在' . SQL非常简单 . ;)

    SELECT DISTINCT t2.field2 
    FROM Table2 t2
    WHERE NOT EXISTS (SELECT * FROM Table1 WHERE t1.field1 = t2.field1)
    

相关问题