SQL查询-不使用嵌套子查询

时间:2018-07-17 15:25:05

标签: sql

表1

ID  SystemID    Description
---------------------------
1   25             Test1
1   25             Test2
2   40             Test1
2   40             Test3
3   26             Test9
3   36             Test5
4   70             Test2
4   70             Test9

表2

ID  Department 
------------------
1   Sales
2   Marketing
3   Accounting
4   Purchasing

我有Table1Table2这两个表。

我需要从Table1中选择所有具有与ID = 1和SystemID = 25相同描述的不同ID,然后从查询结果中从Table2中选择所有行。

有没有一种更好的查询方式,而无需使用嵌套子查询?

select * 
from Table2 
where ID in (select distinct(ID) 
             from Table1 
             where SystemID = 25
               and Description in (select Description 
                                   from Table1 
                                   where ID = 1 and SystemID = 25))

最终输出为

1 Sales
2 Marketing
4 Purchasing

感谢您的帮助。谢谢。

4 个答案:

答案 0 :(得分:1)

我想你想要

select t1.id, t2.department
from table1 t1 join
     table2 t2
     on t1.id = t2.id
where t1.description in (select tt1.description from table1 tt1 where tt1.id = 1 and tt1.systemid = 25);

这是标准的SQL,应该在SQL Server和Oracle中都可以使用。

答案 1 :(得分:1)

相信,这应该会给您相同的结果。除了使用IN而不使用EXISTS之外,还可以使用JOIN来代替进一步的子查询:

SELECT *
FROM Table2 T2
WHERE EXISTS (SELECT 1
              FROM Table1 T1
                   JOIN Table1 T1t ON T1.[Description] = T1t.[Description]
              WHERE T1.ID = T2.ID
                AND T1t.ID = 1 AND T1t.SystemID = 25);

答案 2 :(得分:1)

您还可以使用外部联接的修改来检测值的存在。

SELECT DISTINCT t2.ID, t2.DEPARTMENT
FROM
    table2 AS t2
    INNER JOIN table1 AS t1a ON table2.ID = table1.ID
    LEFT OUTER JOIN table1 AS t1b ON t1b.id = 1 AND t1b.systemID = 25 AND t1b.description = t1a.description
WHERE t1b.ID IS NOT NULL
      AND t1a.systemID = 25

这将过滤出所有没有描述与ID为1且系统ID为25的条目匹配的条目

答案 3 :(得分:0)

SELECT DISTINCT T2.* --Use a distinct for simplicity but a group by is better
FROM Table2 AS T2
INNER JOIN Table1 AS T1_Source ON T1_Source.SystemID = 25 AND T1_Source.ID = 1 
/*^ Find table1 with System and ID 
    Expected Result 
    ID  SystemID    Description
    1   25             Test1
    1   25             Test2

    Note Rows are duplicated use distinct or group by
*/
INNER JOIN Table1 AS T1_Target ON T1_Target.Description = T1_Source.Description
/*^ Find table1 with all the Description matching the result we found
    Expected Result 
    ID  SystemID    Description
    1   25             Test1
    1   25             Test2
    2   40             Test1
    4   70             Test2

     Note Rows are duplicated use distinct or group by
*/