日期:2014-05-18  浏览次数:20344 次

请教 in 查询不到数据?
tableA
11


tableB
10,11
11,12



select * from tableA
where 1 = 1
and tableA.id in ( 11)
-- 这样可以查处数据

select * from tableA
where 1 = 1
and tableA.id in ( 11,12)
-- 这样也可以查处数据


select * from tableA
where 1 = 1
and tableA.id in ( select tableB.id from tableB )
-- 结果一条数据都查询不出来

select * from tableA
where 1 = 1
and tableA.id in ( select top 1 tableB.id from tableB )
-- 加上 top 1 同样查询不出来


------解决方案--------------------
SQL code
create table tableA(id int)
insert into tableA select 11
create table tableB(id int,col int)
insert into tableB select 10,11
insert into tableB select 11,12
go
select * from tableA
where 1 = 1
and tableA.id in ( 11)
-- 这样可以查处数据
/*
id
-----------
11

(1 行受影响)
*/
select * from tableA
where 1 = 1
and tableA.id in ( 11,12)
-- 这样也可以查处数据
/*
id
-----------
11

(1 行受影响)

*/
select * from tableA
where 1 = 1
and tableA.id in ( select tableB.id from tableB )
-- 这样,同样可以查询到数据:
/*
id
-----------
11

(1 行受影响)
*/
select * from tableA
where 1 = 1
and tableA.id in ( select top 1 tableB.id from tableB )
-- 加上 top 1 查询不出来,因为第一个id是10
select * from tableA
where 1 = 1
and tableA.id in ( select top 1 tableB.id from tableB order by id desc)
--这样,还能查出数据
/*id
-----------
11

(1 行受影响)

*/

------解决方案--------------------
select * from tableA
where 1 = 1
and tableA.id in ( select top 1 tableB.id from tableB 
--这个如果不排序的话 子查询中取得的值是无序的。
------解决方案--------------------
探讨
select * from tableA
where 1 = 1
and tableA.id in ( select top 1 tableB.id from tableB
--这个如果不排序的话 子查询中取得的值是无序的。