日期:2014-05-19  浏览次数:20477 次

求一条关于查询的SQL语句
表结构如下
    ID           AID                 PID
    1       3,5,15,23           3,15
    2       5,12,16,21         5,12
    3     2,16,9,5,31           31
    4     15,25,8,9,7         15,9

现要求查询AID中包含同时PID中不包含某个数字的所有记录。
例如要查询包含   5   的记录,要得到如下结果:
    ID           AID                 PID
    1       3,5,15,23           3,15
    3     2,16,9,5,31           31

只能针对   5   ,对15、25等数据中包含的   5   要忽略

------解决方案--------------------
declare @t table (ID int,AID varchar(20),PID varchar(20))
insert @t select
1 , '3,5,15,23 ', '3,15 ' union all select
2 , '5,12,16,21 ', '5,12 ' union all select
3 , '2,16,9,5,31 ', '31 ' union all select
4 , '15,25,8,9,7 ', '15,9 '

select * from @t where charindex( ',5, ', ', '+AID+ ', ')> 0 and charindex( ',5, ', ', '+PID+ ', ')=0
/*
結果:
ID AID PID
----------- -------------------- --------------------
1 3,5,15,23 3,15
3 2,16,9,5,31 31
*/
------解决方案--------------------
rockyljt(江濤) 的没错