SQL查询中缺少FROM子句

时间:2015-08-25 17:45:50

标签: sql postgresql

以下查询不断返回missing FROM-clause entry for table "tags"错误,但我不确定原因:

SELECT tags.id, tags.user_id, LOWER(tags.tag) AS tag, tags.detail, us.email
FROM user_settings us
WHERE NOT EXISTS (
  SELECT 1
  FROM UNNEST(ARRAY[$1]) AS selected_tags(tag)
  LEFT JOIN admin.tags tags
    ON tags.tag = selected_tags.tag
  WHERE tags.user_id = us.id
    AND selected_tags.tag IS NULL
);

2 个答案:

答案 0 :(得分:0)

由于初始SELECT中的LOWER(tags.tag)和tags.detail,您需要进行如下更改(注意:在第一个FROM之后添加另一个LEFT JOIN):

SELECT tags.id, tags.user_id, LOWER(atags.tag) AS tag, atags.detail, pl.email
FROM user_settings us
  LEFT JOIN admin.tags atags
    ON tags.tag = selected_tags.tag
WHERE NOT EXISTS (
  SELECT 1
  FROM UNNEST(ARRAY[$1]) AS selected_tags(tag)
  LEFT JOIN admin.tags tags
    ON tags.tag = selected_tags.tag
  WHERE tags.user_id = us.id
    AND selected_tags.tag IS NULL
);

答案 1 :(得分:0)

您无法从WHERE NOT EXISTS子查询中进行选择。改为使用JOIN。

  SELECT tags.id, tags.user_id, LOWER(tags.tag) AS tag, tags.detail, pl.email
  FROM user_settings us
  JOIN (
    SELECT 1
    FROM UNNEST(ARRAY[$1]) AS selected_tags(tag)
    LEFT JOIN admin.tags tags
      ON tags.tag = selected_tags.tag
    WHERE selected_tags.tag IS NOT NULL
  ) t on t.user_id = us.id ;