2016-04-26 56 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