2016-09-07 65 views
1

有沒有一種方法可以構建一個SQL語句,它將幫助我根據狀態檢索活動記錄,然後引用另一個字段中存儲的oldids?SQL從包含逗號分隔鍵的字段中選擇

假設我想將下面的數據加入到另一個表中。對於ID = 4,意味着暗示ID 1,3和4結合在一起,倖存的記錄是4.

所以,當我想要與另一個表一起加入時,如何將scvid 104鏈接到ID 1,3和4的交易?

select * 
from tbl 
where scvid in (id, oldids)? 

的樣本數據:

scvid id oldid status 
------------------------------ 
101  1  NULL  0 
102  2  NULL  1 
103  3  NULL  0 
104  4  [1,3]  1 
+6

不要將數據存儲爲逗號分隔的項目。這隻會導致你很多麻煩。 – jarlh

+2

你使用什麼數據庫(MSSQL,MySql,....)? – valex

回答

0

你沒有提到你的數據庫系統。這裏是SQL Server(TSQL)的解決方案。您也可以在其他RDBMS有細微的變化

SELECT 
    t1.*, t2.scvid as NEWID 
FROM 
    tbl t1 
JOIN 
    tbl t2 ON 
    -- first case: if the record is main with [1,3] we link it to the the self 
    (t1.scvid = t2.scvid) AND (t2.oldid IS NOT NULL) 
    OR 
    -- second case: we bulid ",1,3," from "[1,3]" 
    -- then we get condition ",1,3," LIKE "%,id,%" 
    -- for the id = 1 and 3 it's TRUE 
    (REPLACE(REPLACE(t2.oldid,'[',','),']',',') 
     LIKE '%,'+CAST(t1.id as VARCHAR(100))+',%') 
    AND (t1.oldid IS NULL) 

結果使用它:

scvid id oldid status NEWID 
101 1 NULL 0   104 
103 3 NULL 0   104 
104 4 [1,3] 1   104 

這本記錄輸出新列NEWIDId這樣你就可以加入或以其他方式使用。

0

對於Postgres,您可以通過將逗號分隔列表轉換爲數組來完成此操作。

事情是這樣的:

樣品設置:

create table some_table (id integer); 
insert into some_table values (4), (6), (8); 

create table service (svcid integer, id integer, oldid text, status integer); 
insert into service 
values 
(101, 1, NULL , 0), 
(102, 2, NULL , 1), 
(103, 3, NULL , 0), 
(104, 4, '1,3', 1); 

some_table獲得的所有行id要麼是service表的id列或任何那些在oldid列中,您可以使用:

select * 
from some_table st 
    join (
    select svcid, id, oldid, status, string_to_array(s.oldid, ',')::int[]||id as all_ids 
    from service s 
) s on st.id = any(s.all_ids) 

返回:

id | svcid | id | oldid | status | all_ids 
---+-------+----+-------+--------+-------- 
4 | 104 | 4 | 1,3 |  1 | {1,3,4} 
0

這適用於SQL Server。
由於LIKE語法支持負數字字符類別爲[^0-9]

select 
old.scvid as old_scvid, old.id as old_id, 
new.scvid as new_scvid, new.id as new_id, new.oldid as new_oldids 
from tbl new 
left join tbl old 
    on (old.status = 0 and new.oldid like concat('%[^0-9]',old.id,'[^0-9]%')) 
    where new.status = 1 
    and new.oldid is not null 

糟糕的是,該表沒有「newid」字段,而不是帶有範圍的「oldid」字段。
這會讓參與更容易。

+0

(標準)SQL LIKE只支持'_'和'%'作爲通配符。 「LIKE」不支持「模式」或類似的「正則表達式」。 –

相關問題