疑难问题,偶太菜鸟不能实现,求高手
数据结构
aidbidcidPID
----------------------------
10110012001121
10110012002121
10110012003121
10110012001122
10110012002122
10110012003122
10110022006121
10110022007121
10110022008121
10210032009123
....
比如说 要查 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 是竖向的结构
如果是横向的结构就好办了,
101A1001A1002B2001B2002B2003B2006B2008B2009
121truetruetrueturetruetrueturetrueture
122truefalsefalseturetruetruefalsefalsefalse
....
只要这样就可以了
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)
/*
aidbidcidPID
10110012001121
10110012001122
10110022006121
10110022008121*/
[解决办法]
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))