如何制作不同的WHERE子句

时间:2012-05-23 22:11:24

标签: php mysql

$data['do'] = $this->db->query("SELECT MONTH(`date`) as month, COUNT(*) as count
FROM `simple` WHERE `ochistka` = 'somevalue' GROUP BY MONTH(`date`)");

这里我选择的是每个月都有一些值的字段,但我如何选择另一个字段与其他条件,而不是计数()作为计数,而是另外一个计数()作为count2,有其他WHERE子句可能吗?

2 个答案:

答案 0 :(得分:4)

如果我理解你正在尝试实现的目标,你可以使用SUM(IF)技巧,如下所示:

SELECT MONTH(`date`) as month,
       SUM(IF(`ochistka` = 'somevalue', 1, 0)) as count1,
       SUM(IF(`ochistka` = 'othervalue', 1, 0)) as count2
FROM `simple`
GROUP BY MONTH(`date`)

答案 1 :(得分:0)

目前无法测试代码,但基本思路是使用子查询:

SELECT t1.month as month, t1.count as count1, t2.count as count2 
FROM
    (SELECT MONTH(`date`) as month, COUNT(*) as count
     FROM `simple` 
     WHERE `ochistka` = 'somevalue' 
     GROUP BY MONTH(`date`)) AS t1
INNER JOIN
    (SELECT MONTH(`date`) as month, COUNT(*) as count 
     FROM `simple` 
     WHERE `ochistka` = 'someothervalue' 
     GROUP BY MONTH(`date`)) AS t2 ON t1.month = t2.month