没有UNION的SQL查询

时间:2009-09-18 11:29:32

标签: sql

任何人都可以在不使用UNION语句的情况下帮助我重写以下查询吗?

(
  SELECT
    A.QRYNAME0 "Query Name",
    A.OPRID,
    A.DESCR,
    A.QRYTYPE,
    TO_CHAR(A.CREATEDTTM,'DD-MON-YYYY HH24:MI:SS') "Created On",
    TO_CHAR(A.LASTUPDDTTM,'DD-MON-YYYY HH24:MI:SS') "Last Updated On",
    B.EXECCOUNT "No of Times Executed",
    B.AVGEXECTIME,
    TO_CHAR(B.LASTEXECDTTM,'DD-MON-YYYY HH24:MI:SS') "Last Executed On"
    --TO_CHAR(SUBSTR(A.DESCRLONG,1,50))"Long Description"
  FROM
    PSQRYDEFN A,
    PSQRYSTATS B
  WHERE
    A.QRYNAME = B.QRYNAME and
    a.oprid = b.oprid
)
UNION
(
  SELECT
    A.QRYNAME "Query Name",
    A.OPRID,
    A.DESCR,
    A.QRYTYPE,
    TO_CHAR(A.CREATEDTTM,'DD-MON-YYYY HH24:MI:SS') "Created On",
    TO_CHAR(A.LASTUPDDTTM,'DD-MON-YYYY HH24:MI:SS') "Last Updated On",
    0 "No of Times Executed",
    0,
    NULL "Last Executed On"
    --TO_CHAR(SUBSTR(A.DESCRLONG,1,50)) "Long Description"
  FROM
    PSQRYDEFN A
  WHERE 
    NOT EXISTS (
      SELECT 1 
      FROM   PSQRYSTATS B
      WHERE  a.qryname = b.qryname and a.oprid = b.oprid
    )
)

3 个答案:

答案 0 :(得分:1)

看起来您正在模拟左外连接。尝试

A.QRYNAME *= B.QRYNAME and
a.oprid *= b.oprid

甚至更好,使其符合ANSI标准

FROM PSQRYDEFN A
LEFT OUTER JOIN PSQRYSTATS B ON A.QRYNAME=B.QRYNAME AND A.oprid=B.oprid

答案 1 :(得分:0)

我认为你正在寻找左外连接和isnull / nvl函数,但不知道SQL的方言,并且表格不能准确

SELECT
    A.QRYNAME0 "Query Name",
    A.OPRID,
    A.DESCR,
    A.QRYTYPE,
    TO_CHAR(A.CREATEDTTM,'DD-MON-YYYY HH24:MI:SS') "Created On",
    TO_CHAR(A.LASTUPDDTTM,'DD-MON-YYYY HH24:MI:SS') "Last Updated On",
    nvl( B.EXECCOUNT, 0 ) "No of Times Executed",
    nvl( B.AVGEXECTIME, 0)
    nvl( TO_CHAR(B.LASTEXECDTTM,'DD-MON-YYYY HH24:MI:SS'), null) "Last Executed On"
    --TO_CHAR(SUBSTR(A.DESCRLONG,1,50))"Long Description"
FROM
    PSQRYDEFN A left outer join   PSQRYSTATS B
     on A.QRYNAME = B.QRYNAME and
         a.oprid = b.oprid

答案 2 :(得分:0)

看起来你需要两个表的LEFT OUTER JOIN,而且你需要使用NVL修改EXECCOUNT和EXECAVGTIME值以将空值转换为零。