简体   繁体   English

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

[英]Retrieving multiple data “Series” with a single mySQL query

Is there a way to combine these two queries into a single one so that I can retrieve two data "series" for charting purposes while still maintaining the relationship for a single date? 有没有一种方法可以将这两个查询合并为一个查询,以便我可以检索两个数据“系列”以用于制图,同时仍保持单个日期的关系?

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;

What I am looking for is output like this: 我正在寻找的是这样的输出:

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

Use the GROUP BY function: 使用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;

That should give you two rows, one for tech=1, one for tech=7. 那应该给你两行,一行代表tech = 1,一行代表tech = 7。 And when you use the GROUP BY function, the COUNT() applies to each grouping. 并且当您使用GROUP BY函数时,COUNT()将应用于每个分组。

In response to updated question, try this: 为了回应更新的问题,请尝试以下操作:

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;

If that is not it, please post some sample data for us to work with. 如果不是这样,请发布一些示例数据供我们使用。

With UNION ALL it will look like 有了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

But GROUP BY is a better approach as @Seth suggested 但是,正如@Seth建议的那样, GROUP BY是更好的方法

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

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