简体   繁体   中英

MySQL case in where clause

I'm having problems with a suspected logic error with a CASE statement in my WHERE clause but I can't see the problem.

SELECT a_id, a_name, a_folder_flag
FROM table_a
LEFT JOIN table_b ON table_a.a_id = table_b.b_a_id
WHERE a_status_id = 1
AND (
CASE
    WHEN a_access_flag = 1
    THEN b_usr_id = 1 OR b_grp_id = 2
    END )
GROUP BY a_id

Basically I want to get all records from table_a but if a_access_flag is 1 then I need to apply the additional where clause filtering in the CASE statement.

Currently it is returning 0 rows when I include the CASE statement.

A case does not make much sense in a where clause. But you can convert that into logic. Try

WHERE a_status_id = 1
AND 
(
  a_access_flag <> 1
  OR (b_usr_id = 1 OR b_grp_id = 2)
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM