在Postgresql中创建一个常量

时间:2013-04-05 15:34:25

标签: postgresql

假设我有这个查询:

select * 
from myTable
where myTable.myCol in (1,2,3)

我想这样做:

with allowed_values as (1,2,3)
select * 
from myTable
where myTable.myCol in allowed_values

它在第一行给出了一个语法错误,你能帮我解决它吗?

4 个答案:

答案 0 :(得分:6)

我能想到的最接近你的语法:

WITH allowed_values (id) AS 
  ( VALUES
      (1), (2), (3)
  )
SELECT * 
FROM myTable
WHERE id IN 
   (TABLE allowed_values) ;

SQL-Fiddle

中进行测试

答案 1 :(得分:3)

接近你可能想到的:

WITH allowed_values AS (SELECT '{1,2,3}'::int[] AS arr)
SELECT * 
FROM   my_table
      ,allowed_values   -- cross join with a single row
WHERE  my_col = ANY (arr);

更好:

WITH allowed_values (my_col) AS (VALUES (1), (2), (3))
SELECT * 
FROM   allowed_values
JOIN   my_table USING (my_col)

但实际上,你可以简化:

SELECT * 
FROM  (VALUES (1), (2), (3)) AS allowed_values (my_col)
JOIN   my_table USING (my_col);

答案 2 :(得分:2)

尝试

with allowed_values as (select 1 as tst union all select 2 union all select 3)    
select * from myTable a
inner join c1 b ON (b.tst = a.myCol)

答案 3 :(得分:2)

最简单的方法是更正公用表表达式,然后在子选择中使用它。

with allowed_values as (
  select 1 id
  union all
  select 2
  union all
  select 3
)
select * from myTable
where myTable.id in (select id from allowed_values)