2016-02-23 96 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