如何使用多个子查询改进SELECT语句

时间:2019-02-13 13:15:21

标签: sql oracle oracle11g subquery

如何更好地改进以下SQL语句?我尝试使用EXCEPT,但无法正常工作。任何建议/建议都非常欢迎!

SELECT COUNT(*)
FROM ( SELECT L_ORDERKEY, COUNT(*)
   FROM LINEITEM
   GROUP BY L_ORDERKEY
   HAVING COUNT(*) > (SELECT DISTINCT TSIZE
                      FROM LINEITEM) );


SELECT LINEITEM.L_ORDERKEY, LINEITEM.L_LINENUMBER
FROM LINEITEM JOIN PART
   ON LINEITEM.L_PARTKEY = PART.P_PARTKEY
WHERE PART.P_PARTKEY IN (46557,20193,19110,45690,45123)
   MINUS
      (SELECT LINEITEM.L_ORDERKEY, LINEITEM.L_LINENUMBER
       FROM LINEITEM JOIN PART
          ON LINEITEM.L_PARTKEY = PART.P_PARTKEY
       WHERE PART.P_PARTKEY IN (46557,20193,19110,45690,45123)
       MINUS
       SELECT LINEITEM.L_ORDERKEY, LINEITEM.L_LINENUMBER
       FROM LINEITEM JOIN SUPPLIER
          ON LINEITEM.L_SUPPKEY = SUPPLIER.S_SUPPKEY
       WHERE SUPPLIER.S_SUPPKEY IN (4567,2323,1987,2194,1111)
      );

1 个答案:

答案 0 :(得分:1)

您可以使用not exists进行第二次查询

   SELECT L.L_ORDERKEY, L.L_LINENUMBER
     FROM LINEITEM L
     JOIN PART P
       ON L.L_PARTKEY = P.P_PARTKEY
    WHERE P.P_PARTKEY IN (46557, 20193, 19110, 45690, 45123)
      AND NOT EXISTS
         (SELECT 0
            FROM SUPPLIER S
           WHERE S.S_SUPPKEY IN (4567, 2323, 1987, 2194, 1111)
             AND L.L_SUPPKEY = S.S_SUPPKEY );