日期:2014-05-17  浏览次数:20367 次

疑难问题,偶太菜鸟不能实现,求高手
数据结构
aid bid cid PID
----------------------------
101 1001 2001 121
101 1001 2002 121
101 1001 2003 121

101 1001 2001 122
101 1001 2002 122
101 1001 2003 122

101 1002 2006 121
101 1002 2007 121
101 1002 2008 121

102 1003 2009 123

....

比如说 要查 aid=101的 bid是1001的 并且cid是2002 或者 2001的 我可以这样查 where aid=101 and((bid=1001 and cid=2002) or (bid=1001 and cid=2001))
这样 就可以查出 pid= 121 122 的记录 
现在 我要查出 aid=101, bid=1001, cid=(2002 或者 2001) 并且 bid=1002 cid=(2006 或者2007 或者2008) 我该怎么查啊?
现在表里有几百万条数据 怎么实现啊 高手进

问题出在表结构bid cid 是竖向的结构
如果是横向的结构就好办了,

101 A1001 A1002 B2001 B2002 B2003 B2006 B2008 B2009
121 true true true ture true true ture true ture
122 true false false ture true true false false false
....

只要这样就可以了
where (A1001=ture and (b2001=true or b2002=true)) and  (A1002=ture and (b2006=true or b2007=true or b2009=true))

 但是横向有问题 列是不固定的

谁能解啊?
疑难问题

------解决方案--------------------
if object_id('[TB]') is not null drop table [TB]
go
create table [TB] (aid int,bid int,cid int,PID int)
insert into [TB]
select 101,1001,2001,121 union all
select 101,1001,2002,121 union all
select 101,1001,2003,121 union all
select 101,1001,2001,122 union all
select 101,1001,2002,122 union all
select 101,1001,2003,122 union all
select 101,1002,2006,121 union all
select 101,1002,2007,121 union all
select 101,1002,2008,121 union all
select 102,1003,2009,123

select * from [TB]

DECLARE @a VARCHAR(100)
DECLARE @b VARCHAR(MAX)
DECLARE @c VARCHAR(MAX)
DECLARE @sql VARCHAR(MAX)

SET @a = '101'
SET @b = '1001,1002'
SET @c = '2001,2006,2008'
SET @sql = 'SELECT * FROM TB WHERE aid ='+ @a +'AND bid IN ('+@b+') AND cid IN ('+@c+')'

EXEC(@sql)

/*
aid bid cid PID
101 1001 2001 121
101 1001 2001 122
101 1002 2006 121
101 1002 2008 121*/

------解决方案--------------------
try this,

select * from [表名]
where (aid=101 and bid=1001 and cid in(2001,2002))
or(aid=101 and bid=1002 and cid in(2006,2007,2008))