为什么此查询会导致“缺少FROM子句”?

时间:2018-11-22 08:14:44

标签: sql postgresql

为什么下面的sql语句不断丢失表错误的FROM子句条目?
如何调整呢?

WITH SUBID AS (
    SELECT * FROM "B_COLLECTION"."COLL_C_RECORD"
),
TR AS (
  SELECT * FROM "B_TRACE"."PERSONAL_TC_RECORD"
)
SELECT "SUBJECT_C_ID" 
FROM "B_COLLECTION"."COLL_C_RECORD"
WHERE ( SUBID.SUBJECT_ID = TR.PERSONAL_S_ID ) 
  AND ( TR.STATE_ID ='5' OR TR.STATE_ID  = 'A' OR TR.STATE_ID = 'C');

1 个答案:

答案 0 :(得分:0)

您正在声明SUBID和TR很好,但是由于它们是表,因此您的select语句尚不知道它们。

在这里,您需要在查询的FROM子句中输入SUBID和TR。它应该看起来像

WITH SUBID AS (
        SELECT * FROM "B_COLLECTION"."COLL_C_RECORD"
                  ) ,
        TR AS (
                      SELECT * FROM "B_TRACE"."PERSONAL_TC_RECORD"
                  )
SELECT "SUBJECT_C_ID" FROM SUBID
WHERE SUBID."SUBJECT_ID" IN 
   (SELECT "PERSONAL_S_ID" FROM TR
    WHERE TR."STATE_ID" = '5'
    OR TR."STATE_ID" = 'A'
    OR TR."STATE_ID" = 'C');

这就是为什么只在重复查询中使用WITH子句的原因。在这里使用起来实际上会更容易:

SELECT "SUBJECT_ID" FROM "B_COLLECTION"."COLL_C_RECORD" SUBID
WHERE SUBID."SUBJECT_ID" IN 
  (SELECT "PERSONAL_S_ID" FROM "B_TRACE"."PERSONAL_TC_RECORD" TR
   WHERE TR."STATE_ID" = '5'
   OR TR."STATE_ID" = 'A'
   OR TR."STATE_ID" = 'C');