我正在处理一个SQL查询,其中有两个表名为Theatre,Movies like this:
剧场
Theatre with columns theatre id and show date:
id show_date
------------------
1 2018-05-01
2 2018-05-01
1 2018-05-03
3 2018-05-04
2 2018-05-14
3 2018-05-11
2 2018-05-14
电影
Movie with columns movie id and movie name:
id name
----------
1 Avatar
2 Spiderman
3 Avengers
预期的结果是:(我为每一行添加了注释作为解释)
theatre_id show_date movie
---------------------------------------------
1 2018-05-01 Avatar /* 1st theatre, 1st date occurrence so picking 1st movie
2 2018-05-01 Avatar /* 2nd theatre, 1st date occurrence so picking 1st movie */
1 2018-05-03 Avatar /* 1st theatre, with 1 day gap (1st may 2018 to 3rd may 2018), so picking 1st movie
3 2018-05-04 Avatar /* 3rd theatre, 1st date occurrence so picking 1st movie */
2 2018-05-10 Spiderman /* 2nd theatre, with 8 days gap (1st may 2018 to 10th may 2018), so picking 2nd movie */
3 2018-05-11 Spiderman /* 3rd theatre, with 6 days gap (4th may 2018 to 11th may 2018) so picking 2nd movie */
2 2018-05-14 Avengers /* 2nd theatre, with 3 days gap (10th may 2018 to 14th may 2018), so picking 3rd movie */
drop table if exists theatre;
CREATE TABLE theatre (
id INTEGER NOT NULL,
show_date date NOT NULL
);
drop table if exists movie;
CREATE TABLE movie (
id INTEGER NOT NULL PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(60) NOT NULL
);
insert into movie values (null, 'Avatar');
insert into movie values (null, 'Spiderman');
insert into movie values (null, 'Avengers');
insert into theatre values( 1, cast('2018-05-01' as date));
insert into theatre values( 2, cast('2018-05-01' as date));
insert into theatre values( 1, cast('2018-05-03' as date));
insert into theatre values( 3, cast('2018-05-04' as date));
insert into theatre values( 2, cast('2018-05-10' as date));
insert into theatre values( 3, cast('2018-05-11' as date));
insert into theatre values( 2, cast('2018-05-14' as date));