2012-10-04 90 views
0

我有一個表plist與列list,其中包含逗號分隔的ID(1,2,3,4)。我想要那些id不在逗號分隔列表中的成員的記錄。SQL查詢來查找記錄無法在其他表

+1

哪個RDBMS? SQL Server,MySQL發等 – hims056

+5

唯一有效的答案應該是「重新設計你的DB模式和關於規範化寫着」您正在使用哪個數據庫服務器 – fancyPants

回答

1

,最好的辦法是將逗號分隔列表分裂成一個表,然後搜索反對。

這裏是分割字符串代碼:

DECLARE @YourTable table (RowID int, Layout varchar(200)) 
INSERT @YourTable VALUES (1,'1,2,3,4') 

;WITH SplitSting AS 
(
    SELECT 
     RowID,LEFT(Layout,CHARINDEX(',',Layout)-1) AS Part 
      ,RIGHT(Layout,LEN(Layout)-CHARINDEX(',',Layout)) AS Remainder 
     FROM @YourTable 
     WHERE Layout IS NOT NULL AND CHARINDEX(',',Layout)>0 
    UNION ALL 
    SELECT 
     RowID,LEFT(Remainder,CHARINDEX(',',Remainder)-1) 
      ,RIGHT(Remainder,LEN(Remainder)-CHARINDEX(',',Remainder)) 
     FROM SplitSting 
     WHERE Remainder IS NOT NULL AND CHARINDEX(',',Remainder)>0 
    UNION ALL 
    SELECT 
     RowID,Remainder,null 
     FROM SplitSting 
     WHERE Remainder IS NOT NULL AND CHARINDEX(',',Remainder)=0 
) 
SELECT RowID,part FROM SplitSting ORDER BY RowID 
+0

? –

+0

我正在使用SQL服務器 – AnandPhadke