使用null结果计算mysql中的枚举值

时间:2016-11-08 07:15:39

标签: mysql sql

我有一个名为" user"

的表
user_id|Name|employment_type|gender
------------------------------------
1      |ABC |salaried       |MALE
2      |DEF |salaried       |Male 

employment_type = enum('薪水',' self_employed')

我想计算具有employment_type = salaried和self_employed的行数。 在上面的例子中,我想要像这样的结果

employment_type | count
-----------------------
salaried        |2
self_employed   |0

但是我的查询给了我以下结果

employment_type | count
-----------------------
salaried        |2

我的查询:

SELECT employment_type ,COUNT(employment_type) as "count"
FROM users WHERE user_id IN(1,2) AND employment_type IN ("salaried","self_employed") GROUP BY employment_type

请帮助我获得所需的结果,谢谢

2 个答案:

答案 0 :(得分:1)

您可以通过引入一个所有employment types所在的表来实现此目的。

SELECT
emp_type,
COUNT(users.employment_type) AS count
FROM
(
    SELECT  "salaried" AS emp_type
    UNION 
    SELECT "self_employed"
) AS empTypeTable
LEFT JOIN users ON users.employment_type = empTypeTable.emp_type
    AND
    user_id IN (1, 2)
    AND 
    employment_type IN (
      "salaried",
      "self_employed"
     )
GROUP BY
    empTypeTable.emp_type;

然后在LEFT JOIN的帮助下,您将获得所有就业类型的结果。

答案 1 :(得分:0)

对于这种特殊情况(一个明确定义的数字,就业类型的选项数量较少),您可以执行以下操作:

SELECT SUM(qty), employment_type FROM (
    SELECT COUNT(0) AS qty, employment_type FROM users WHERE user_id IN(1,2) AND employment_type IN ("salaried","self_employed") GROUP BY employment_type
    UNION 
    SELECT 0 AS qty, "salaried" AS employment_type 
    UNION 
    SELECT 0 AS qty, "self_employed" AS employment_type 
) t
GROUP BY employment_type ;

诀窍是使用"帮助表"它由单个select语句组成 - 通过union连接它们,然后在表和单个语句上分组。