2016-02-23 95 views
-2

我自己找到了答案。但是,引起很多人在搜索,我想这样分享我的解决方案SAM的事情:MySQL COUNT在WHERE OR语句

我的示例表:

t_employes     t_increases 
id | name | salary   employe_id | year 
------------------   ----------------- 
1 | Jon | 3000    1   | 2005 
2 | Ben | 3000    1   | 2008 
3 | Tom | 2499    2   | 2007 

我需要什么:

SELECT 
    t_employes.name, 
    t_employes.salary, 
    COUNT(t_increases.employe_id) AS count_increases 
FROM 
    t_employes 
    LEFT JOIN t_increases ON t_employes.id = t_increases.employe_id 
WHERE 
    t_employes.salary < 2500 
    -- OR count_increases < 2 -- (error) 
    -- OR COUNT(t_increases.employe_id) -- (error) 
GROUP BY t_employes.name 

我不能使用具有因为我需要我的条件在一个或声明

+0

你可以把两个或运算条件HAVING子句。或者两个查询联合在一起,一个用HAVING子句,另一个用来检查工资。 – Kickstart

+0

有100种方法可以解决这个问题。但是我希望它在聚合之前发生。现在,我还可以将它与我无法在HAVING子句中使用的条件结合起来。这就是为什么我要求解决方案将其放在WHERE子句中。看标题。我回答了。它的工作原理。那么为什么评级很差呢?由于您的解决方案是唯一的解决方案 –

+0

我还没有评价过。你的解决方案的问题仅仅在于性能,因为mysql往往不能很好地用子查询优化IN子句。不知道为什么你觉得你不能在having子句中使用OR。 – Kickstart

回答

0

这一个正在使用WHERE clausel中的COUNT语句:

SELECT 
    t_employes.name, 
    t_employes.salary, 
    COUNT(t_increases.employe_id) AS count_increases 
FROM 
    t_employes 
    LEFT JOIN t_increases ON t_employes.id = t_increases.employe_id 
WHERE 
    t_employes.salary < 2500 OR 
    t_employes.id IN (SELECT employe_id FROM t_increases GROUP BY employe_id HAVING COUNT(year) < 2) 
GROUP BY t_employes.id 
+0

这就是为什么mysql'GROUP BY'很奇怪。在其他dbms中,您应该使用'..GROUP BY t_employes.name,t_employes.salary..',因为您将这些列放在没有集合函数的select语句中。 – RubahMalam

+0

那么最新的问题? – sagi

0

2种避免子查询的解决方案。

首先在HAVING子句中检查计数和工资。

SELECT 
    t_employes.name, 
    t_employes.salary, 
    COUNT(t_increases.employe_id) AS count_increases 
FROM 
    t_employes 
    LEFT JOIN t_increases ON t_employes.id = t_increases.employe_id 
GROUP BY t_employes.name 
HAVING t_employes.salary < 2500 
OR count_increases < 2 

第二个解决方案,它确实2个查询,每一个条件,并使用UNION合并在一起的结果

SELECT 
    t_employes.name, 
    t_employes.salary, 
    COUNT(t_increases.employe_id) AS count_increases 
FROM 
    t_employes 
    LEFT JOIN t_increases ON t_employes.id = t_increases.employe_id 
WHERE 
    t_employes.salary < 2500 
GROUP BY t_employes.name 
UNION 
SELECT 
    t_employes.name, 
    t_employes.salary, 
    COUNT(t_increases.employe_id) AS count_increases 
FROM 
    t_employes 
    LEFT JOIN t_increases ON t_employes.id = t_increases.employe_id 
GROUP BY t_employes.name 
HAVING count_increases < 2