cinema
table?
| seat_id | free | |---------|------| | 1 | 1 | | 2 | 0 | | 3 | 1 | | 4 | 1 | | 5 | 1 |Your query should return the following result for the sample case above.
| seat_id | |---------| | 3 | | 4 | | 5 |Note:
join
and abs()
[Accepted]Intuition
\nThere is only one table in this problem, so we probably need to use self join for this relative complex problem.
\nAlgorithm
\nFirst, let\'s see what we have after joining this table with itself.
\n\n\nNote: The result of join two tables is the Cartesian product of these two tables.
\n
select a.seat_id, a.free, b.seat_id, b.free\nfrom cinema a join cinema b;\n
seat_id | \nfree | \nseat_id | \nfree | \n
---|---|---|---|
1 | \n1 | \n1 | \n1 | \n
2 | \n0 | \n1 | \n1 | \n
3 | \n1 | \n1 | \n1 | \n
4 | \n1 | \n1 | \n1 | \n
5 | \n1 | \n1 | \n1 | \n
1 | \n1 | \n2 | \n0 | \n
2 | \n0 | \n2 | \n0 | \n
3 | \n1 | \n2 | \n0 | \n
4 | \n1 | \n2 | \n0 | \n
5 | \n1 | \n2 | \n0 | \n
1 | \n1 | \n3 | \n1 | \n
2 | \n0 | \n3 | \n1 | \n
3 | \n1 | \n3 | \n1 | \n
4 | \n1 | \n3 | \n1 | \n
5 | \n1 | \n3 | \n1 | \n
1 | \n1 | \n4 | \n1 | \n
2 | \n0 | \n4 | \n1 | \n
3 | \n1 | \n4 | \n1 | \n
4 | \n1 | \n4 | \n1 | \n
5 | \n1 | \n4 | \n1 | \n
1 | \n1 | \n5 | \n1 | \n
2 | \n0 | \n5 | \n1 | \n
3 | \n1 | \n5 | \n1 | \n
4 | \n1 | \n5 | \n1 | \n
5 | \n1 | \n5 | \n1 | \n
To find the consecutive available seats, the value in the a.seat_id should be more(or less) than the value b.seat_id, and both of them should be free.
\nselect a.seat_id, a.free, b.seat_id, b.free\nfrom cinema a join cinema b\n on abs(a.seat_id - b.seat_id) = 1\n and a.free = true and b.free = true;\n
seat_id | \nfree | \nseat_id | \nfree | \n
---|---|---|---|
4 | \n1 | \n3 | \n1 | \n
3 | \n1 | \n4 | \n1 | \n
5 | \n1 | \n4 | \n1 | \n
4 | \n1 | \n5 | \n1 | \n
At last, choose the concerned column seat_id, and display the result ordered by seat_id.
\n\n\nNote: You may notice that the seat with seat_id \'4\' appears twice in this table. This is because seat \'4\' next to \'3\' and also next to \'5\'. So we need to use
\ndistinct
to filter the duplicated records.
MySQL
\nselect distinct a.seat_id\nfrom cinema a join cinema b\n on abs(a.seat_id - b.seat_id) = 1\n and a.free = true and b.free = true\norder by a.seat_id\n;\n