MySQL Query包含两个包含不同日期的表

时间:2016-08-26 11:00:26

标签: mysql join

我有一个小问题我处理得不好。 我需要从两个表中导出一些数据。两个表只包含两个字段。第一个是日期时间,第二个是包含值。 我想按日期对这些数据进行分组。让我用一个例子来解释。

表A:

@import url('//cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.css');
@import url('//cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.theme.min.css');

.owl-centered .owl-wrapper {
  display: table !important;
}
.owl-centered .owl-item {
  display: table-cell;
  float: none;
  vertical-align: middle;
}
.owl-centered .owl-item > div {
  text-align: center;
}

输出:

<div id="owl-example" class="owl-carousel owl-centered">
  <div><img src="//placehold.it/120x120/69c/fff/" alt=""></div>
  <div><img src="//placehold.it/200x200/c69/fff/" alt=""></div>
  <div><img src="//placehold.it/160x160/9c6/fff/" alt=""></div>
  <div><img src="//placehold.it/240x240/fc6/fff/" alt=""></div>
  <div><img src="//placehold.it/160x160/9c6/fff/" alt=""></div>
  <div><img src="//placehold.it/200x200/c69/fff/" alt=""></div>
  <div><img src="//placehold.it/120x120/69c/fff/" alt=""></div>
</div>

<script src="//code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/owl-carousel/1.3.3/owl.carousel.min.js"></script>

表B:

SELECT * FROM tableA order by Time desc limit 10;

如您所见,时间值不相等。我想从两个表,组和图中获取值。图表不是问题。我希望,例如,每5分钟为每个表取一个值。 任何帮助都会被贬低!

谢谢!

西蒙

1 个答案:

答案 0 :(得分:1)

分组为5分钟(300秒)。如果多个值落入一个间隔,则取最大值。

select  from_unixtime(U*300) as date,
        max(if(T='A',val,NULL)) as A_VAL,
        max(if(T='B',val,NULL)) as B_VAL
  from (
    select ceil(unix_timestamp(date)/300) as U, val, 'A' as T
      from tableA
      WHERE date BETWEEN '2016-08-26 12:20:00' AND '2016-08-26 12:55:00'
    union all
    select ceil(unix_timestamp(date)/300) as U, val, 'B' as T
      from tableB
      WHERE date BETWEEN '2016-08-26 12:20:00' AND '2016-08-26 12:55:00'
   ) A
 group by U
 order by U

结果:

2016-08-26 12:15:00 NULL    29.5
2016-08-26 12:20:00 26.900  29.6
2016-08-26 12:25:00 27.200  29.6
2016-08-26 12:30:00 27.100  30.0
2016-08-26 12:35:00 27.000  30.0
2016-08-26 12:40:00 26.500  30.1
2016-08-26 12:45:00 26.800  30.1
2016-08-26 12:50:00 26.900  29.8
2016-08-26 12:55:00 27.000  29.9
2016-08-26 13:00:00 NULL    30.1

Sample on sqlfiddle.com