2

假设我有这个查询:

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

4 回答 4

6

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

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

SQL-Fiddle中测试

于 2013-04-05T19:14:32.507 回答
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);
于 2013-04-05T19:58:38.227 回答
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)
于 2013-04-05T15:48:23.887 回答
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)
于 2013-04-05T19:03:16.573 回答