我自己找到了答案。但是导致很多人在寻找我想要的山姆的东西,所以分享我的解决方案:
我的示例表:
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
我无法使用HAVING,因为我需要在OR语句中使用我的条件
答案 0 :(得分: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
答案 1 :(得分: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