如何在不使用临时变量的情况下在MariaDB中创建日期序列?

时间:2017-12-09 22:32:33

标签: sql mariadb

数据库架构参考:http://sqlzoo.net/wiki/Guest_House

对一系列日期的请求始于提出这样的问题:在某个日期开始的完整周期间,谁在特定的房间?请求是列出所有房间空的日子 换句话说,输出应如下所示:

+------------+-----------+
| i          | last_name |
+------------+-----------+
| 2016-11-21 | McDonnell |
| 2016-11-22 | McDonnell |
| 2016-11-23 | Whitford  |
| 2016-11-24 | Whitford  |
| 2016-11-25 | NULL      |
| 2016-11-26 | NULL      |
| 2016-11-27 | Berry     |
+------------+-----------+

尝试解决它导致过度使用两个临时变量!请参阅下面的sql脚本。

SELECT @row := '2016-11-20' as var1;
SELECT @row2 := '2016-11-20' as var2;

select t1.cur_date as i, t2.last_name
from
(select @row2 := ADDDATE(@row2, 1) as cur_date from booking LIMIT 7) as t1
LEFT JOIN (
select cur_date, gg.last_name
from booking as bb CROSS JOIN
(select @row := ADDDATE(@row, 1) as cur_date from booking LIMIT 7) as dd
INNER JOIN guest as gg ON bb.guest_id = gg.id
where bb.room_no = 207
and ADDDATE(bb.booking_date, bb.nights) >= ADDDATE(cur_date, 1)
and bb.booking_date <= cur_date
) as t2 USING (cur_date)

关于如何简化这个或者一般如何在一组日期中执行sql查询而不用临时变量执行可能的黑客方法的任何想法?

1 个答案:

答案 0 :(得分:1)

您可以使用序列存储引擎(https://mariadb.com/kb/en/library/sequence-storage-engine/)简化操作,而不必使用@row变量来构建序列,该引擎默认是从MariaDB 10.1安装的。

SELECT d.date, 
 (
      SELECT b.last_name
      FROM booking AS a
      LEFT JOIN guest AS b
      ON a.guest_id = b.id
      WHERE a.room_no = '207' 
      AND a.booking_date <= d.date 
      AND a.booking_date + INTERVAL nights DAY > d.date
 )
 FROM 
 (
      SELECT '2016-11-21' + INTERVAL (seq) DAY AS date
      FROM seq_0_to_7
 ) AS d;