SQL select语句动态多重条件

时间:2010-08-16 20:19:14

标签: sql sql-server select

我有3个表,比如images(id), news(id), types(id, category, obj_id, type)

例如,新闻A的类别为黑色,红色。

data struct就像

{
  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.

因为,就像这样,它将返回图像_B,C,D,E。我只需要images_B。

类别也是动态的。它可能是红色,蓝色,粉红色......

1 个答案:

答案 0 :(得分: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 obj_id=@target)