2016-04-26 26 views
0

我正在使用PostgreSQL。如果我有一个ID在查询说:即使重复也在ID IN查询中检索相同数量的记录

select * from public.record where id in (1,5,1); 

这样只会给我两行,因为ID 1有重复。但是如果我想显示一组记录,包含如下内容:

id | value 
1 | A 
5 | B 
1 | A 

无论我为什么要这样做,这是可能的吗?

回答

2

你可以做到这一点的加入值:

with ids (id) as (
    values (1),(5),(1) 
) 
select r.* 
from public.record r 
    join ids on r.id = ids.id; 

如果你需要保持参数列表的顺序,你需要添加一列进行排序:

with ids (id, sort_order) as (
    values 
     (1, 1), 
     (5, 2), 
     (1, 1) 
) 
select r.* 
from public.record r 
    join ids on r.id = ids.id 
order by ids.sort_order; 
+0

我接受了这个答案,因为它允许我插入ID更容易与没有太多的字符串操作不像其他答案..然而我upvoted两个..谢谢 – muffin

+0

只是一个后续行动,如果你可以,我怎么分开一个在“(1),(5),(1)”中的括号括在括号中的某些id的字符串,如“1,5,1”。 – muffin

1

您可以使用JOIN一个子查询:

SELECT 
    r.id, r.value 
FROM public.record r 
INNER JOIN (
    SELECT 1 AS id UNION ALL 
    SELECT 5 AS id UNION ALL 
    SELECT 1 AS id 
) t 
    ON t.id = r.id 
0

如果要求将结果中的所有行(1,5,1) t包括不匹配public.record然后使用OUTER连接

with c(id) as (
    values (1),(5),(1) 
) 
select r.* 
from c 
left join public.record pr 
on pr.id = c.id; 

编辑
如果输入是一个字符串类型的“1,5,1” SQL注入安全的代码应该把它作为一个参数,不是代码。

declare @prm varchar(1000) ='1,5,1'; 

select r.* 
from DelimitedSplit8K(@prm) c 
left join public.record pr 
on pr.id = cast(c.item as int); 

哪里DelimitedSplit8K是杰夫MODEN的功能(MS SQL)http://www.sqlservercentral.com/articles/Tally+Table/72993/或您选择的任何其他分离器。

+0

如何在“(1),(5),(1)”中将一串如“1,5,1”的id分隔为括号中的内容。 – muffin

+0

@muffin您也可以在Sql中分隔分隔字符串。请参阅http://www.sqlservercentral.com/articles/Tally+Table/72993/图21显示了代码,它运行速度很快。 – Serg