使用CTE = ANY

时间:2017-04-26 19:04:48

标签: postgresql

查询:

WITH first_names AS (SELECT DISTINCT fname FROM voters) 
SELECT name 
from nicknames 
WHERE groupi = (
    SELECT nn.groupi 
    FROM nicknames AS nn 
    WHERE name = 'john'
) AND name != 'john' AND upper(name) = ANY(first_names);

错误: column "first_names" does not exist

如何从select创建数组并在where语句中使用它?

2 个答案:

答案 0 :(得分:0)

try JOIN instead of ANY

WITH first_names AS (SELECT DISTINCT fname FROM voters) 
SELECT name 
from nicknames 
JOIN first_names on fname = upper(name)
WHERE groupi = (SELECT nn.groupi FROM nicknames AS nn WHERE name = 'john') AND name != 'john' 
;

答案 1 :(得分:0)

你在这里混淆辅助语句名称和列。 first_names是您SELECT DISTINCT提供的结果的名称,fname是其中包含的列的名称。

不评论整体查询的正确性,更正的语句将使用正确的列名。

WITH first_names AS (SELECT DISTINCT fname
                     FROM voters)
SELECT name
FROM nicknames
WHERE groupi = (
  SELECT nn.groupi
  FROM nicknames AS nn
  WHERE name = 'john'
) AND name != 'john' AND upper(name) = ANY (first_names.fname);