使用单个mySQL查询检索多个数据“Series”

时间:2013-04-12 16:04:18

标签: php mysql charts report

有没有办法将这两个查询合并为一个查询,以便我可以检索两个数据“系列”以进行图表处理,同时仍保持单个日期的关系?

SELECT 
        COUNT(j.id) AS power_count, jd.ber_rcvd 
    FROM
        jobs j 
        INNER JOIN job_dates jd 
            ON jd.job_id = j.id 
    WHERE j.tech = 7 AND jd.ber_rcvd != '0000-00-00' GROUP BY jd.ber_rcvd;
SELECT 
        COUNT(j.id) AS transport_count, jd.ber_rcvd 
    FROM
        jobs j 
        INNER JOIN job_dates jd 
            ON jd.job_id = j.id 
    WHERE j.tech = 1 AND jd.ber_rcvd != '0000-00-00' GROUP BY jd.ber_rcvd;

我正在寻找的是这样输出:

power_count | transport_count | ber_rcvd
11 | 3 | 2013-03-01
7 | 1 | 2013-03-02

2 个答案:

答案 0 :(得分:4)

使用GROUP BY功能:

SELECT j.tech, COUNT( j.id ) AS ber_count 
FROM job j
    INNER JOIN job_dates jd ON jd.job_id = j.id
WHERE j.tech IN ( 7, 1 )
GROUP BY j.tech;

那应该给你两行,一个用于tech = 1,一个用于tech = 7。当您使用GROUP BY函数时,COUNT()适用于每个分组。

在回答更新的问题时,请尝试以下方法:

SELECT COUNT( IF(j.tech=7,1,NULL)) AS power_count, COUNT( IF( j.tech = 1, 1, NULL )) AS transport_count, jd.ber_rcvd
FROM
    jobs j 
    INNER JOIN job_dates jd 
        ON jd.job_id = j.id 
WHERE j.tech IN ( 1, 7 ) AND jd.ber_rcvd != '0000-00-00' 
GROUP BY jd.ber_rcvd;

如果不是,请发布一些样本数据供我们使用。

答案 1 :(得分:1)

使用UNION ALL,它看起来像

SELECT COUNT(j.id) AS ber_count, jd.ber_rcvd 
  FROM jobs j 
       INNER JOIN job_dates jd 
               ON jd.job_id = j.id 
 WHERE j.tech = 7
 UNION ALL
SELECT COUNT(j.id) AS ber_count, jd.ber_rcvd 
  FROM jobs j 
       INNER JOIN job_dates jd 
               ON jd.job_id = j.id 
 WHERE j.tech = 1

GROUP BY是一种更好的方法,因为@Seth建议