结合两个MySQL查询?

时间:2012-08-25 05:56:56

标签: php mysql

$query1 = 'select DATE_FORMAT(time, "%Y-%m-%d") as date,
        count(*) as phone_TotalPerDay
        from numrequest
        where id_usr = "'.$id_user.'"
        AND id_re ="'.$id_re.'"
        AND request="ph"
        group by id_usr, year(time), DAYOFYEAR(time)
        order by year(time) DESC, DAYOFYEAR(time) DESC';  


$query2 = 'select DATE_FORMAT(time, "%Y-%m-%d") as date,
        count(*) as fax_TotalPerDay
        from numrequest
        where id_usr = "'.$id_user.'"
        AND id_re ="'.$id_re.'"
        AND request="fx"
        group by id_usr, year(time), DAYOFYEAR(time)
        order by year(time) DESC, DAYOFYEAR(time) DESC';  

有没有办法将这两个查询结合起来。我真的需要它们在一个资源中。 目前每个人每天都会显示号码请求的数量。我想将它们组合起来,以便每个date都有phone_TotalPerDayfax_TotalPerDay

1 个答案:

答案 0 :(得分:1)

您可以使用条件总和,例如

$query1 = 'select DATE_FORMAT(time, "%Y-%m-%d") as date,
    sum(if(request = "ph", 1, 0)) phone_TotalPerDay,
    sum(if(request = "fx", 1, 0)) fax_TotalPerDay
    from numrequest
    where id_usr = "'.$id_user.'"
    AND id_re ="'.$id_re.'"
    group by id_usr, year(time), DAYOFYEAR(time)
    order by year(time) DESC, DAYOFYEAR(time) DESC';

如果请求类型匹配,则if语句返回1,否则返回0,因此对这些语句进行求和会有效计算符合此条件的行,并且我已从where子句中删除了请求条件。