【问题标题】:mysql nested query with 4 queries带有4个查询的mysql嵌套查询
【发布时间】:2014-06-23 18:31:49
【问题描述】:

我对 mysql 查询有疑问, 事实上,我必须建立一个带有图表的网页,我需要从数据库中获取数据,如下所示:

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

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

3- 获取当前年份每个中心每月未完成且日期超过 20 天的数据总数。

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

| monthname | total | totalNotDone | totalExceed20Days |
|  January  | 52    |    3         |      1            |
|  February | 48    |    4         |      0            |
|  March    | 54    |    1         |      3            |

等等

这是一个显示问题的 sqlfiddle:

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

任何帮助将不胜感激,我真的被困住了。

【问题讨论】:

  • 那个小提琴里有很多不相关的信息,不是吗?摆脱它,然后回到我们身边。
  • 请在此处发布相关信息。显示表的架构、一些示例输入数据以及您尝试过的查询。
  • 正如@Barmar 指出的那样,最好将相关信息放在问题中。
  • 这是一个 sqlfiddle sqlfiddle.com/#!2/8cc9c/1

标签: mysql sqlfiddle


【解决方案1】:

您的基本查询没问题。您需要做的是将它们中的每一个都视为一个虚拟表,并将它们LEFT JOIN 放在一起。然后您的顶级SELECT 可以为您的整个表格选择适当的值。

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

请注意,这是按 center_id 和日期汇总的,因此您可以在单个查询中获取所有 center_id 值。

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

您拥有的是三个子查询,三个虚拟表(如果您愿意),每个表包含三列:日期、center_id 和总计。你LEFT JOIN他们在一起ON其中两列。

我不得不稍微处理一下您的查询,以使它们具有相似的列名和列数据格式,因此 LEFT JOIN 操作具有常规结构。

【讨论】:

  • 非常切割,不知道那种嵌套,非常好的技巧:)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-25
相关资源
最近更新 更多