错误:使用IN时,子查询返回的行多于1

时间:2019-07-08 17:36:40

标签: mysql

我有一个问题,为什么我在IF中使用IN时查询是错误的

SET @level  := '2';
SET @id_user    := '2';

SELECT *
FROM pg_akun
WHERE 
    level_akun = @level
    AND parent_id_akun IN (
        IF(@level IN ('1', '2'), (SELECT DISTINCT(parent_id_akun) FROM pg_akun WHERE level_akun = @level), @id_user)
    )
    AND id_akun NOT IN (SELECT id_akun FROM pg_trans WHERE id_user = '1' AND pengajuan = '1')

报告错误

Query: select * from pg_akun where level_akun = @level AND parent_id_akun in ( if(@level in ('1', '2'), (SELECT DISTINCT(parent_id_akun...

Error Code: 1242.
Subquery returns more than 1 row

1 个答案:

答案 0 :(得分:1)

IF必须返回一个值,它不能返回可在IN中使用的派生表。

IF移到IN之外。

SELECT *
FROM pg_akun
WHERE 
    level_akun = @level
    AND IF(@level IN ('1', '2'),
            parent_id_akun IN (SELECT DISTINCT parent_id_akun FROM pg_akun WHERE level_akun = @level),
            parent_id_akun = @id_user)
    AND id_akun NOT IN (SELECT id_akun FROM pg_trans WHERE id_user = '1' AND pengajuan = '1')

顺便说一句,DISTINCT不是适用于单个列的函数,它是适用于整个SELECT列表的关键字。您不需要在列名两边加上括号。