简体   繁体   English

结合两个MySQL查询?

[英]Combining two MySQL queries?

$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';  

Is there a way to combine these two queries. 有没有办法组合这两个查询。 I really need them in one resource. 我真的很需要它们。 currently each one is showing number of number request per day. 目前,每个人每天都在显示请求数量 I want to combine them so that each date has phone_TotalPerDay and fax_TotalPerDay . 我想将它们组合在一起,以便每个date都具有phone_TotalPerDayfax_TotalPerDay

You could use a conditional sum, something like 您可以使用条件和,例如

$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';

The if statements return 1 if the request type matches and 0 otherwise, so summing these effectively counts the rows matching this condition, and I've removed the request criteria from the where clause. if请求类型匹配, if语句返回1,否则返回0,因此对这些语句求和将对与该条件匹配的行进行有效计数,并且我从where子句中删除了请求条件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM