问题描述:
几个朋友来到电影院的售票处,准备预约连续空余座位。
你能利用表 cinema ,帮他们写一个查询语句,获取所有空余座位,并将它们按照 seat_id 排序后返回吗?
| seat_id | free |
|---------|------|
| 1 | 1 |
| 2 | 0 |
| 3 | 1 |
| 4 | 1 |
| 5 | 1 |
对于如上样例,你的查询语句应该返回如下结果。
| seat_id |
|---------|
| 3 |
| 4 |
| 5 |
注意:
seat_id 字段是一个自增的整数,free 字段是布尔类型('1' 表示空余, '0' 表示已被占据)。
连续空余座位的定义是大于等于 2 个连续空余的座位。
DDL(拿去即可运行)
/*
Navicat Premium Data Transfer
Source Server : 本地数据库
Source Server Type : MySQL
Source Server Version : 80013
Source Host : localhost:3306
Source Schema : rxttest
Target Server Type : MySQL
Target Server Version : 80013
File Encoding : 65001
Date: 23/09/2021 14:37:42
*/
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for cinema1
-- ----------------------------
DROP TABLE IF EXISTS `cinema1`;
CREATE TABLE `cinema1` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`seat_id` int(100) DEFAULT NULL,
`free` int(2) DEFAULT NULL,
PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of cinema1
-- ----------------------------
INSERT INTO `cinema1` VALUES (1, 1, 1);
INSERT INTO `cinema1` VALUES (2, 2, 0);
INSERT INTO `cinema1` VALUES (3, 3, 1);
INSERT INTO `cinema1` VALUES (4, 4, 1);
INSERT INTO `cinema1` VALUES (5, 5, 1);
SET FOREIGN_KEY_CHECKS = 1;
思路:自连接,条件是相邻且空闲。
sql语句,拿去即可运行
select DISTINCT c1.seat_id from cinema1 c1,cinema1 c2
where c1.free=1 and c2.free=1 and abs(c1.seat_id-c2.seat_id)=1 ORDER BY c1.seat_id desc
我要刷100道算法题,第61道