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

不能作:“子查询用作表达式时”
select id from BhB 
  where Bh in (select bh from bhb where glid=(select glid from bhb where bh='10838318'))

这句是可以执行的,当放在case when中,

 select id from BhB where Bh in (
  case when(select glid from bhb where bh='10838318')=0
then (select bh from bhb where  bh='10838318') 
else (select bh from bhb where glid=(select glid from bhb where bh='10838318'))
 end)

就出现错误,“子查询返回的值不止一个。当子查询跟随在 =、!=、<、<=、>、>= 之后,或子查询用作表达式时,这种情况是不允许的。”

是不能作:“子查询用作表达式时”
该怎么解决?

请高手帮助

------解决方案--------------------
分支呗
if
elseif
else

------解决方案--------------------
子查询里面有大于1条的数据,要是取得的bh有不同的几条数据,就会报错;
如果是重复的,可以用一下方法改正:


 select id from BhB where Bh in (
  case when(select distinct glid from bhb where bh='10838318')=0
then (select distinct bh from bhb where  bh='10838318') 
else (select distinct bh from bhb where glid=(select distinct glid from bhb where bh='10838318'))
 end)


------解决方案--------------------
glid=(select glid from bhb where bh='10838318')
这句的问题
当括号里的查询只返回一条记录时,不会报错。
当括号里的查询返回多条记录时,就会报你那个错,因为无法把一个值和多个值用等号比较。

处理方法要么是保证后面的查询只返回一条记录,如创建唯一索引,或者在确保查询语义正确的情况下把=改成in
------解决方案--------------------
if (select glid from bhb where bh='10838318')=0 --如果返回多条会报错
  select id from BhB where Bh in (select bh from bhb where  bh='10838318') 
else
select id from BhB 
   where Bh in (select bh from bhb where glid=(select glid from bhb where bh='10838318'))
 
------解决方案--------------------
case when 是表达式,而你那个是集合,所以报错
------解决方案--------------------

--建议改用exists
select id from BhB t1
  where exists (select bh from bhb t2 where  t2.bh=t1.bh
and exists(select 1 from bhb b3 where t2.glid=t3.glid and bh='10838318'))

------解决方案--------------------
因为你使用了子查询,而当子查询返回多于1个值的时候