我有一个问题,为什么我在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
答案 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
列表的关键字。您不需要在列名两边加上括号。