我有一张表,有五个字段。如
字段一 字段二 字段三 字段四 字段五
1 A B C D
2 C D E F
一般情况查询情况如下:
select 字段一 form 表 where 字段二= 'A ' and 字段三= 'B ' and 字段四= 'C ' and 字段四= 'D '
如果这四个参数顺序是随机的。如果一般查询就会造成以下结果。
select 字段一 form 表 where 字段二= 'D ' and 字段三= 'B ' and 字段四= 'A ' and 字段四= 'C '
这时候SQL语句怎样写,可以得到正确的结果?
------解决方案--------------------
一般情况查询情况如下:
select 字段一 form 表 where 字段二= 'A ' and 字段三= 'B ' and 字段四= 'C ' and 字段四= 'D '
-------
打錯了吧,應是字段五吧
------解决方案--------------------
---上面的可能不准
create table tab(字段一 int,字段二 varchar(1),字段三 varchar(1),字段四 varchar(1),字段五 varchar(1))
insert tab
select 1, 'A ', 'B ', 'C ', 'D '
union select 2, 'C ', 'D ', 'E ', 'F '
declare @str1 varchar(10),@str2 varchar(10),@str3 varchar(10),@str4 varchar(10)
select @str1= 'D ',@str2= 'B ',@str3= 'A ',@str4= 'C '
---用临时表
select id=identity(int,1,1),c into #
from (
select [email protected]
union select [email protected]
union select [email protected]
union select [email protected]) t
select *
from tab
where 字段二=(select c from # where id=1)
and 字段三=(select c from # where id=2)
and 字段四=(select c from # where id=3)
and 字段五=(select c from # where id=4)
drop table #
drop table tab
------解决方案--------------------
如果这四个参数顺序是随机的。如果一般查询就会造成以下结果。
select 字段一 form 表 where 字段二= 'D ' and 字段三= 'B ' and 字段四= 'A ' and 字段四= 'C '
把所有的组合加起来?
select 字段一 form 表 where 字段二= 'A ' and 字段三= 'B ' and 字段四= 'C ' and 字段五= 'D '
union all
select 字段一 form 表 where 字段二= 'A ' and 字段三= 'C ' and 字段四= 'B ' and 字段五= 'D '
.....
select 字段一 form 表 where 字段二= 'D ' and 字段三= 'B ' and 字段四= 'C ' and 字段五= 'A '
------解决方案--------------------
还是不对啊.乌龟的也不对.