mysql奇怪的in /​​ =任何带子查询的运算符的行为

时间:2014-08-06 13:06:28

标签: mysql sql

我有以下查询:

select * from rootTable rt
where
  (select pk
   from someConfigTable
   where col1='someValue') = any(select confRef from t where t.r = rt.r)
and rt.pk = 123

(select pk from someConfigTable where col1='someValue')会返回一些数字3456789 select confRef from t where t.r = rt.r会返回一些数字3456789, 3456789 someConfigTable.pkt.confRef的类型为bigint(20)

但由于某种原因,查询不会返回任何行!

但是,当我用常量替换(select pk from someConfigTable where col1='someValue')时,它可以正常工作并返回一些行:

select * from rootTable rt
where 3456789 = any(select confRef from t where t.r = rt.r) and rt.pk = 123

问题是什么???

show variables like '%version%'

# Variable_name, Value
innodb_version, 5.6.16
protocol_version, 10
slave_type_conversions, 
version, 5.6.16
version_comment, MySQL Community Server (GPL)
version_compile_machine, x86_64
version_compile_os, Win64

3 个答案:

答案 0 :(得分:0)

select * from rootTable rt
 where (select pk from someConfigTable where col1='someValue') in (select confRef from t          
  where t.r = rt.r) and rt.pk = 123

试试这个:)但我不是100%肯定它会正常工作???

答案 1 :(得分:0)

您正在尝试比较两个数字集合。有趣。 SQL没有很好地将列表与列表进行比较。请尝试使用明确的join。我认为这抓住了逻辑:

select rt.*
from rootTable rt join
     t
     on t.r = rt.r
where rt.pk = 123 and
      t.confref in (select pk from someConfigTable where col1 = 'someValue');

如果select distinct中的多行符合条件,则可能需要t

或者,您的原始查询可能适用于exists子句:

 where exists (select 1
               from someConfigTable sct join
                    t
                    on sct.pk = t.confReg
               where sct.col1 = 'someValue' and
                     t.r = rt.r
              )

答案 2 :(得分:0)

如果你只想要一条记录。

select * from rootTable rt
where
  (select pk
   from someConfigTable
   where col1='someValue' LIMIT 1) = any(select confRef from t where t.r = rt.r)
and rt.pk = 123

条件: 1:rootTable应该有列 - > rootTable列名必须是someConfigTable.pk值

select pk
       from someConfigTable
       where col1='someValue' LIMIT 1

返回列名。超过一列不被接受,因为。

它会是这样的

where Name , Fname =value --wrong!

这就是你想要的吗?