从多个表的字段创建摘要视图

iaqfqrcu  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(312)

我正在尝试编写一个select查询来在mysql中创建一个视图。视图中的每一行都应该显示从多个表中收集的用户值的每周摘要(sum,avg)。这些表彼此相似,但不完全相同。视图还应该包括行,以防其他表没有该周的值。像这样:

| week_year | sum1 | avg1 | sum2 | user_id |
| --------- | ---- | ---- | ---- | ------- |
| 201840    |      |      | 3    | 1       |
| 201844    | 45   | 55   |      | 1       |
| 201845    | 55   | 65   |      | 1       |
| 201849    | 65   | 75   |      | 1       |
| 201849    | 75   | 85   | 3    | 2       |

表(简化)如下:

CREATE TABLE IF NOT EXISTS `t1` (
  `user_id` INT NOT NULL AUTO_INCREMENT,
  `date` DATE NOT NULL,
  `value1` int(3) NOT NULL,
  `value2` int(3) NOT NULL,
  PRIMARY KEY (`user_id`,`date`)
) DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `t2` (
  `id` INT NOT NULL AUTO_INCREMENT,
  `date` DATE NOT NULL,
  `value3` int(3) NOT NULL,
  PRIMARY KEY (`id`)
) DEFAULT CHARSET=utf8;

CREATE TABLE IF NOT EXISTS `t3` (
  `t3_id` INT NOT NULL,
  `user_id` INT NOT NULL
) DEFAULT CHARSET=utf8;

我当前的解决方案似乎不合理,我不确定它在数千行的情况下会如何执行:

select ifnull(yearweek(q1.date1), yearweek(q1.date2)) as week_year,
       sum(value1)                             as sum1,
       avg(value2)                              as avg1,
       sum(value3)                                   as sum2,
       q1.user_id
from (select t2.date as date2,
             t1.date as date1,
             ifnull(t3.user_id, t1.user_id) as user_id,
             t1.value1,
             t1.value2,
             t2.value3
      from t2
             join t3 on t3.t3_id=t2.id
             left join t1 on yearweek(t1.date) = yearweek(t2.date) and t1.user_id = t3.user_id
      union
      select t2.date as date2,
             t1.date as date1,
             ifnull(t3.user_id, t1.user_id) as user_id,
             t1.value1,
             t1.value2,
             t2.value3
      from t2
             join t3 on t3.t3_id=t2.id
             right join t1 on yearweek(t1.date) = yearweek(t2.date) and t1.user_id = t3.user_id) as q1

group by week_year, user_id;

小提琴
当前的解决方案在性能方面还可以吗?还是有更好的选择?如果将来添加第三个(或第四个)表,我将如何管理查询?我应该考虑创建一个单独的表,用触发器更新吗?
提前谢谢。

y3bcpkx1

y3bcpkx11#

另一种方法是合并所有数据,然后将其分组。您必须进行性能测试,看看哪一个更好:

SELECT

  yearweek(date), 
  SUM(value1) as sum1,
  AVG(value2) as avg1,
  SUM(value3) as sum2
FROM
(
  SELECT user_id, date, value1, value2, CAST(null as INT) as value3 FROM t1
  UNION ALL 
  SELECT user_id, date, null, null, value3 FROM t2 INNER JOIN t3 ON t2.id = t3.t3_id
)
GROUP BY
  user_id,
  yearweek(date)

希望mysql不会对将null转换为int有异议。。

相关问题