带有IN子句的案例

时间:2013-10-05 07:12:21

标签: mysql

我的查询看起来像,

SELECT `OFFER_ASSIGNED_TO`,
(CASE WHEN `OFFER_ASSIGNED_TO` IN (SELECT GROUP_CONCAT(`EMP_ID` SEPARATOR ',') FROM `f_employee_master` WHERE (`HEAD_OF_EMP`=13 OR `SUPERVISER_ADMIN`=13) AND is_active='Y') THEN 'Y' ELSE 'N' END) HI
FROM f_offer_master

WHERE fy_id=6

结果像这样

OFFER_ASSIGNED_TO   HI
              13    N
              42    N
              13    N
              25    N
              45    N
              25    N

以下查询的结果:

SELECT GROUP_CONCAT(`EMP_ID` SEPARATOR ',') FROM `f_employee_master` WHERE (`HEAD_OF_EMP`=13 OR `SUPERVISER_ADMIN`=13) AND is_active='Y'

is=5,8,9,10,20,21,22,25,29,33,34,35,41

当我写查询时:

SELECT `OFFER_ASSIGNED_TO`,
(CASE WHEN `OFFER_ASSIGNED_TO` IN (5,8,9,10,20,21,22,25,29,33,34,35,41) THEN 'Y' ELSE 'N' END) HI
FROM f_offer_master

WHERE fy_id=6

我得到结果:

OFFER_ASSIGNED_TO   HI
              13    N
              42    N
              13    N
              25    Y
              45    N
              25    Y

这实际上是正确的结果。

但为什么我的第一个查询没有给我正确的结果。

1 个答案:

答案 0 :(得分:0)

SELECT GROUP_CONCAT(`EMP_ID` SEPARATOR ',') FROM `f_employee_master` WHERE (`HEAD_OF_EMP`=13 OR `SUPERVISER_ADMIN`=13) AND is_active='Y'

给出了一个结果。结果是一个字符串,即“5,8,9,10,20,21,22,25,29,33,34,35,41”。

将其与IN一起使用相当于IN ('5,8,9,10,20,21,22,25,29,33,34,35,41'),而不是IN(5,8,9,10,20,21,22,25,29,33,34,35,41)。要获得后者,你必须摆脱GROUP_CONCAT,如下:

CASE WHEN `OFFER_ASSIGNED_TO` IN (SELECT `EMP_ID` FROM ...