首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >带有4个查询的mysql嵌套查询

问带有4个查询的mysql嵌套查询
EN

Stack Overflow用户
提问于 2014-06-23 18:31:49
回答 1查看 224关注 0票数 0

对于mysql查询,我有一个问题,实际上,我必须用图表构建一个网页,我需要从数据库中获取数据,如下所示:

1-获取本年度每个中心(平均国家)每月收到的数据总数,

2-获取本年度每个中心每月未完成的数据总数,

3-获取本年度每个中心每月超过20天未完成的数据。

因此,总之,我能够为所有这些查询获取数据,这没有问题。我面临的问题是,我需要将这些查询嵌入到一个单独的查询中,返回一个这样的表:

代码语言:javascript
复制
| monthname | total | totalNotDone | totalExceed20Days |
|  January  | 52    |    3         |      1            |
|  February | 48    |    4         |      0            |
|  March    | 54    |    1         |      3            |

等。

下面是一个显示问题的sqlfiddle:

编辑:http://sqlfiddle.com/#!2/8cc9c/1

任何帮助都是非常感谢的,伙计们,我真的被困住了。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-06-23 18:58:00

您的基本查询都很好。您需要做的是将每个虚拟表作为一个虚拟表,并将它们放在一起LEFT JOIN。然后,您的toplevel SELECT可以为整个表选择适当的值。

代码语言:javascript
复制
SELECT afftotal.date,
       afftotal.centre_id,
       afftotal.total AS total,
       af20.total AS total_20,
       afempty.total AS total_empty
FROM (
    /* select total of affaires per month and per centre for this year */
select month(aff_date) AS `date`,
       centre_id,
       count(*) AS `total` 
    from affaires
    where year(aff_date) = 2014 
    group by month(aff_date), centre_id
 ) AS afftotal
LEFT JOIN (
  /* select total of affaires per month and per centre for this year where the affaire has been done
     before 20 days.  */
select month(`affaires`.`aff_date`) AS `date`,
       centre_id,
       count(*) AS `total` 
    from `affaires`
    where year(`affaires`.`aff_date`) = 2014 
    and DATEDIFF(`affaires`.`aff_date`, `affaires`.`date_creation_pdl`) > 20
    group by monthname(`affaires`.`aff_date`), centre_id
 ) AS af20   ON afftotal.date = af20.date
            AND afftotal.centre_id = af20.centre_id
LEFT JOIN (

   /* select total of affaires where the date_creation_pdl is empty */

select month(affaires.aff_date) as `date`, 
       centre_id,
       count(*) as total
from affaires
where date_creation_pdl is null
and year(affaires.aff_date) = 2014
group by monthname(affaires.aff_date)
 ) AS afempty   ON afftotal.date = afempty.date 
               AND afftotal.centre_id = afempty.centre_id

ORDER BY afftotal.centre_id, afftotal.date

http://sqlfiddle.com/#!2/d563e/24/0

注意,这是centre_id和date的总结,所以您可以在一个查询中获得所有的centre_id值。

还请注意,ORDER BY子句放在整个查询的末尾。

您所拥有的是三个子查询、三个虚拟表(如果需要的话),每个表都有三列:日期、centre_id和总计。您可以将它们合并为LEFT JOIN,ON中的两列。

为了使查询具有类似的列名和列数据格式,我不得不对您的查询做一些修改,因此LEFT JOIN操作有一个规则的结构。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/24372897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档