子查询返回多于1行的错误,尽管我使用的是“ IN”关键字

时间:2019-01-19 11:08:29

标签: mysql mysqli

尽管我使用的是"IN"关键字,但我不断收到Subquery returns more than 1 row错误。

这是我的查询:

SELECT * 
FROM `message` 
WHERE `id_receiver` IN ( 
    IF( `to_`='user' , '36' , 
        IF( `to_`='group' , ( 
            SELECT `id` 
            FROM   ( 
                     SELECT * 
                     FROM   `user_position` 
                     ORDER BY `id`) `user_position`, 
                    (SELECT @pv := '100') INITIALISATION 
            WHERE  FIND_IN_SET( `parent_id` , @pv ) > 0 
                AND @pv := concat( @pv , ',' , `id` ) 
            ), ( 
            SELECT `message_group`.`id` 
            FROM   `message_group` 
            LEFT JOIN `message_group_member` 
                   ON `message_group_member`.`id_group`=`message_group`.`id`
            WHERE     `message_group_member`.`id_user`='36' 
        )
    ) 
)
AND `seen`='0'
AND `receiver_delete`='0'
AND `till_date` IS NULL

1 个答案:

答案 0 :(得分:0)

内部select查询返回多行。 if表达式中不允许这样做。可以在纯in表达式中允许它,但是一旦您使用if,它就不再成立。

因此将您的想法转化为一系列OR

SELECT * 
FROM   message 
WHERE  seen = '0'
  AND  receiver_delete ='0'
  AND  till_date IS NULL
  AND  (   (to_ = 'user'  AND id_receiver = '36')
       OR  (to_ = 'group' AND id_receiver IN ( 
            SELECT id 
            FROM   ( 
                     SELECT   * 
                     FROM     user_position 
                     ORDER BY id) user_position, 
                     (SELECT @pv := '100') initialisation 
            WHERE  FIND_IN_SET(parent_id, @pv) > 0 
               AND @pv := concat(@pv , ',' , id) 
           ))
       OR  (to_ NOT IN ('user', 'group') AND id_receiver IN (
            SELECT message_group.id 
            FROM   message_group 
            LEFT JOIN message_group_member 
                   ON message_group_member.id_group=message_group.id
            WHERE     message_group_member.id_user='36' 
           ))
       ) 

我注意到您在第一个内部查询中使用了变量分配。对此请谨慎,因为不能保证执行顺序。我看到该子查询的灵感来自another answer of mine,但请注意该答案中的所有免责声明和警告。他们在这里适用。

如果可以,请移至MySql 8和递归with语法。