2010-08-16 112 views
1

我有3個表,說images(id), news(id), types(id, category, obj_id, type)SQL SELECT語句動態多conditon

例如,新聞類是黑色,紅色。

數據結構是一樣

{ 
    types(xxxx1,red,news_A,news) 
    types(xxxx2,black,news_A,news) 
} 

現在我需要找出型紅色和黑色的所有圖像。

在這種情況下,我需要images_B

{ 
    types(oooo1,red,images_B,images) 
    types(oooo2,black,images_B,images) 
    types(oooo3,red,images_C,images) 
    types(oooo4,red,images_D,images) 
    types(oooo5,black,images_E,images) 
} 

很顯然,我不能寫

select obj_id from types 
where category in (select category from types where obj_id = news_A) 
and type = images. 

因爲,這樣,它會返回images_B,C,d,E。我只需要images_B。

類別也是動態的。這可能是紅色,藍色,粉紅色......

回答

1

一種方法

SELECT * INTO #types 
FROM 
(SELECT 'xxxx1' AS id,'red' AS category,'news_A' AS obj_id,'news' AS [type] UNION ALL 
SELECT 'xxxx2' AS id,'black' AS category,'news_A' AS obj_id,'news' AS [type] UNION ALL 
SELECT 'oooo1' AS id,'red' AS category,'images_B' AS obj_id,'images' AS [type] UNION ALL 
SELECT 'oooo2' AS id,'black' AS category,'images_B' AS obj_id,'images' AS [type] UNION ALL 
SELECT 'oooo3' AS id,'red' AS category,'images_C' AS obj_id,'images' AS [type] UNION ALL 
SELECT 'oooo4' AS id,'red' AS category,'images_D' AS obj_id,'images' AS [type] UNION ALL 
SELECT 'oooo5' AS id,'black' AS category,'images_E' AS obj_id,'images' AS [type]) X 

declare @target varchar(10) 
set @target = 'news_A' 

;with ConcatTypes As 
(
SELECT obj_id, 
    (
     select distinct '' + t.[category] as cat 
     from #types t 
     where t.obj_id = t1.obj_id 
     order by cat 
     for xml path('') 
    ) as catlist 
FROM #types t1 
GROUP BY obj_id 
) 
SELECT obj_id, catlist 
FROM ConcatTypes 
WHERE obj_id<> @target and catlist = 
      (select catlist FROM ConcatTypes where [email protected]) 
+0

THX馬丁。但是我不能像你所描述的那樣硬編碼[types]。真正的類型表是線表 – ValidfroM 2010-08-16 21:03:11

+0

thouands您不必。這一點僅用於演示目的。只需跳過這一點,然後用'; with ConcatTypes As'開始,然後從那裏的'types'表中選擇。我已經將它改爲現在引用臨時表。 – 2010-08-16 21:07:09

+0

+1非常聰明。 – 2010-08-16 21:17:28