I'm making a query that behaves differently when an admin user uses it compared to when a regular user uses it (in a reporting environment).
When an admin views, I want the report to run over all users. When a regular user uses it, I want the query to only look at users working under the current user.
I'm trying to make 1 report, so 1 query, that combines both aspects. My guess was this:
SELECT * FROM datatable dt WHERE dt.user_id IN (
IF (currentUserAdmin = 1, (SELECT id FROM user), (SELECT id FROM user WHERE working_under = currentUserID))
)
(please imagine that currentUserAdmin
and currentUserID
are parameters passed to the stored procedure containing the report query, and that datatable
is actually some real table)
The problem is that mysql says "Subquery returns more than 1 row". Well, I'd say that's the whole idea, because I'm trying to use this with an IN
clause.
What can I do to make this query work?
why not join the tables ?
SELECT dt.* ,user.id FROM datatable dt
INNER JOIN user ON user.id = dt.user_id
WHERE currentUserAdmin = 1
Or working_under = currentUserID