MySQL:取决于WHERE结果的不同行为

时间:2013-06-17 14:15:40

标签: mysql where

我正在修改现有项目。我想将3个mysql请求组合在一起。

这3个请求具有相同的选定数据,只有WHERE更改。 这是例子的要求之一:

SELECT COUNT(seg.my_seg1) FROM (
SELECT COUNT(DISTINCT cp.conference_id) as my_seg1 FROM A.Account a
INNER JOIN A.ConferenceParticipant cp ON a.account_id = cp.user_id
INNER JOIN A.Conference cf ON cf.id = cp.conference_id
WHERE cf.`status` = 0
AND DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= cf.creation_timestamp
GROUP BY a.account_id) as seg
WHERE seg.my_seg1 >= 30

除了以下两个请求完全相同:

WHERE seg.my_seg1 >= 11 AND seg.my_seg1 <= 30;

和:

WHERE seg.my_seg1 >= 30;

所以我的问题是如何根据同一请求中的WHERE结果获得3个不同的值?

1 个答案:

答案 0 :(得分:0)

像这样你将拥有3个虚拟列:

SELECT 
    COUNT(IF(seg.my_seg1 >= 30, 1, 0)) AS res1,
    COUNT(IF(seg.my_seg1 >= 11 AND seg.my_seg1 < 30, 1, 0)) AS res2
FROM (
    SELECT COUNT(DISTINCT cp.conference_id) as my_seg1 
    FROM A.Account a
            JOIN A.ConferenceParticipant cp ON a.account_id = cp.user_id
            JOIN A.Conference cf ON cf.id = cp.conference_id
    WHERE 
        cf.`status` = 0
    AND DATE_SUB(CURDATE(), INTERVAL 30 DAY) <= cf.creation_timestamp
    GROUP BY a.account_id
) AS seg

但你必须修改你的过滤器,你谈到3但我只看到2个不同的过滤器。