0

我有一个查询,我使用 2 UNIONS 来获得我需要的结果

可以使用 CASE 语句来完成,但我无法弄清楚。如果有人能解决这个问题,我将不胜感激

这是我当前的查询,请记住 viewable_by 只能是 1、2 或 3 但是,client_id、team_id 和 created_by 将是一个变量,具体取决于用户,它们会改变

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)

这是我在 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.') '
                                    );
4

2 回答 2

1
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))

是最简单的方法吗

此外,对于 mysql,请记住 UNION 将删除重复项,而这不会。

如果您可以将逻辑约束限制为每个查询的同一组列,则可以将所有 OR 和 UNION 替换为 WHERE ROW(所有列)IN(所有值)。但鉴于您对每个查询的要求非常不同,我认为 OR 是您最好的选择。

于 2013-04-02T23:58:35.957 回答
1

你可以像这样组合它们:

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)
)

您还可以使用SELECT .... WHERE IN语句来组合 OR 语句。

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

将翻译为

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

但是IN我相信在逻辑上等同于OR's 的子句在查询执行方面完全不同

于 2013-04-02T23:59:46.637 回答