case when 在sql 中非常方便数据不同维度统计,但是也会出现mysql 索引不命中问题,当多个case 出现时,需要提取出来到where里面优化
优化后
SELECT
date(RecordTime) AS date,
count(
DISTINCT CASE
WHEN `Param` = '1' THEN
UserID
END
) AS 'h',
count(
DISTINCT CASE
WHEN `Param` = '2' THEN
UserID
END
) AS 's',
count(
DISTINCT CASE
WHEN `Param` = '4' THEN
UserID
END
) AS 'z'
FROM
user_prop_log_202310
WHERE
Category = '42'
GROUP BY
DATE(RecordTime)
优化前:
SELECT
date(RecordTime) AS date,
count(
DISTINCT CASE
WHEN `Category` = '42'
AND `Param` = '1' THEN
UserID
END
) AS 'h',
count(
DISTINCT CASE
WHEN `Category` = '42'
AND `Param` = '2' THEN
UserID
END
) AS 's',
count(
DISTINCT CASE
WHEN `Category` = '42'
AND `Param` = '4' THEN
UserID
END
) AS 'z'
FROM
user_prop_log_202310
GROUP BY
DATE(RecordTime)