【问题标题】:How to do a Select in a Select如何在选择中进行选择
【发布时间】:2009-04-17 15:42:33
【问题描述】:

我有一个包含唯一 ID 字段的表。另一个字段 (REF) 包含对另一个数据集 ID 字段的引用。 现在我必须选择 REF 指向不存在的数据集的所有数据集。

SELECT * FROM table WHERE ("no dataset with ID=REF exists")

我该怎么做?

【问题讨论】:

    标签: sql


    【解决方案1】:

    三种方式

    SELECT * FROM YourTable y WHERE NOT EXISTS 
         (SELECT * FROM OtherTable o WHERE y.Ref = o.Ref)
    
    SELECT * FROM YourTable WHERE Ref NOT IN 
         (SELECT Ref FROM OtherTable WHERE Ref IS NOT NULL)
    
    SELECT y.* FROM YourTable y 
    LEFT OUTER JOIN  OtherTable o ON y.Ref = o.Ref
    WHERE o.Ref IS NULL
    

    另见Five ways to return all rows from one table which are not in another table

    【讨论】:

      【解决方案2】:

      试试这个:

      SELECT * FROM TABLE WHERE NOT EXISTS 
           (SELECT * FROM OtherTable WHERE TABLE.Ref = OtherTable.ID)
      

      【讨论】:

        【解决方案3】:

        我认为这应该可行

        SELECT * FROM table WHERE id NOT IN (SELECT ref_id FROM ref_table)
        

        或与 JOIN

        SELECT table.* 
        FROM table LEFT JOIN ref_table ON table.id = ref_table.ref_id
        WHERE ref_table.ref_id IS NULL
        

        【讨论】:

          【解决方案4】:
          SELECT 
           table1.* 
          FROM 
           table1
           LEFT JOIN table2 ON table1.id = table2.ref
          WHERE 
           table2.ref IS NULL
          

          【讨论】:

            【解决方案5】:

            您可以执行如下子查询:

            select * from table where somefield not in (select otherfield from sometable where ID=REF)
            

            【讨论】:

            • 你不能在(选择 *... 因为一个字段不能评估多个字段)中的某个字段
            【解决方案6】:
            SELECT * 
            FROM table 
            WHERE ((SELECT COUNT(*) FROM table2 WHERE table2.id = table.ref) = 0)
            

            【讨论】:

            • 哈哈哈! -2 分,我很高兴至少代码可以工作,即使它不是最整洁的,否则谁知道少了多少分!
            【解决方案7】:

            类似的东西:

            SELECT * FROM table WHERE ID NOT IN(SELECT REF FROM Table2 )
            

            【讨论】:

              【解决方案8】:

              是的,你可以使用

              select * from x where not exist (select * from y)

              【讨论】:

                猜你喜欢
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 1970-01-01
                • 2021-06-02
                • 2014-03-17
                • 1970-01-01
                • 1970-01-01
                • 2018-11-22
                相关资源
                最近更新 更多