即时创建表

时间:2016-02-02 10:22:16

标签: sql postgresql

在PosgreSQL中,通常可以方便地创建“表格”,以便引用它们,例如。

with

selected_ids as (
select 1 as id
)

select *
from someTable
where id = (select id from selected_ids)

以这种方式提供id多个值是不可能的吗?我发现this answer建议使用values来解决类似问题,但我将其转换为以下示例时遇到问题。

我想写一些子查询,例如

select 1 as id
union
select 2 as id
union
select 7 as id

select 1 as id, 'dog' as animal
union
select 7 as id, 'cat' as animal

以更浓缩的方式,不重复自己。

3 个答案:

答案 0 :(得分:1)

你应该像这样使用union和IN语句:

with
selected_ids as (
select 1 as id
union
select 2 as id
union
select 3 as id
....
)
select *
from someTable
where id in (select id from selected_ids)

在审核wingedpanther's想法并寻找它之后,您可以使用他的想法,如果这些ID不断是这样的:

with
selected_ids as (
SELECT * FROM generate_series(Start,End) --(1,10) for example
)
select *
from someTable
where id in (select id from selected_ids)

如果它们不是连续的,那么你能做到这一点的唯一方法就是将这些ID存储在不同的表中(也许你已经拥有它,如果没有,也可以插入它)

然后:

select *
from someTable
where id in (select id from OtherTable)

答案 1 :(得分:1)

您可以在查询别名中使用参数:

with selected_ids(id) as (
    values (1), (3), (5)
)
select *
from someTable
where id = any (select id from selected_ids)

您也可以使用join代替子查询,例如:

create table some_table (id int, str text);
insert into some_table values
(1, 'alfa'),
(2, 'beta'),
(3, 'gamma');

with selected_ids(id) as (
    values (1), (2)
)
select *
from some_table
join selected_ids
using(id);

 id | str  
----+------
  1 | alfa
  2 | beta
(2 rows)

答案 2 :(得分:1)

您可以像这样

在WITH中传递idanimal字段
with selected_ids(id,animal) as (
values (1,'dog'), (2,'cat'), (3,'elephant'),(4,'rat')--,..,.. etc
)
select *
from someTable
where id = any (select id from selected_ids)