这个带有2个联合的sql可以最小化到没有联合吗? [关闭]

I have a query that I use 2 UNIONS to get the results that I need

It may be done using a CASE statement but I could not figure it out. I will appreciated it if some can can solve this problem

This is my current query please keep in mind that viewable_by can be only 1, 2 or 3 However, client_id, team_id and created_by will be a variable depending on the user those will change

SELECT view_name, view_id, viewable_by  FROM `phone_call_views`
WHERE status = 1 AND ( viewable_by = 1  AND client_id = 1)
UNION
SELECT view_name, view_id, viewable_by  FROM `phone_call_views`
WHERE status = 1 AND ( viewable_by = 2  AND team_id =5 AND client_id = 1)
UNION
SELECT view_name, view_id, viewable_by  FROM `phone_call_views`
WHERE status = 1 AND ( viewable_by = 3  AND created_by= 6)

This is my actual query with the variable in php

$db->getDataSet(' SELECT view_name, view_id, viewable_by  FROM `phone_call_views`
                                     WHERE status = 1 AND ( viewable_by = 1  AND client_id = '.CLIENT_ID.')
                                     UNION
                                     SELECT view_name, view_id, viewable_by  FROM `phone_call_views`
                                     WHERE status = 1 AND ( viewable_by = 2  AND team_id ='.TEAM_ID.' AND client_id = '.CLIENT_ID.')
                                     UNION
                                     SELECT view_name, view_id, viewable_by  FROM `phone_call_views`
                                     WHERE status = 1 AND ( viewable_by = 3  AND created_by= '.USER_ID.') '
                                    );

You can combine them like this:

SELECT view_name, view_id, viewable_by  FROM `phone_call_views`
WHERE status = 1 AND (
   (viewable_by = 1  AND client_id = 1) or 
   (viewable_by = 2  AND team_id =5 AND client_id = 1) or 
   (viewable_by = 3  AND created_by= 6)
)

You can also use SELECT .... WHERE IN statement to combine the OR statements.

Like

SELECT * FROM ... WHERE viewable_by IN (1,2,3)

Will translate to

SELECT * FROM ... WHERE viewable_by='1' or viewable_by='2' or viewable_by='3'

But IN clauses I believe while logically equivalent to OR's are not at all the same when it comes to query execution

SELECT view_name, view_id, viewable_by  FROM `phone_call_views`
WHERE status = 1 AND ( (viewable_by = 1  AND client_id = 1) OR 
( viewable_by = 2  AND team_id =5 AND client_id = 1) OR ( viewable_by = 3  AND created_by= 6))

Is the easiest way to do it

Also, with mysql, remember that UNION will remove duplicates and this will not.

If you can limit your logical constraints to the same set of columns for each query you can replace all the OR's and UNION's with WHERE ROW(all your columns) IN (all your values). But given that you have very different requirements per query, I think the OR's are your best bet.