溶液#1(使用NOT EXISTS
):
SELECT
*
FROM seat S
WHERE NOT EXISTS(
SELECT 1
FROM `date-seat` DS
WHERE DS.seat_id = S.seat_id
AND DS.date_booked ='2016-05-12'
)
AND S.type = 2;
WORKING DEMO
溶液#2(使用LEFT JOIN
和IS NULL
):
SELECT
S.*
FROM seat S
LEFT JOIN `date-seat` DS
ON S.seat_id = DS.seat_id AND DS.date_booked = '2016-05-12'
WHERE S.type = 2 AND DS.seat_id IS NULL;
WORKING DEMO
解決方案#3(使用NOT IN
):
SELECT
*
FROM seat S
WHERE S.seat_id NOT IN (
SELECT DS.seat_id
FROM `date-seat` DS
WHERE DS.date_booked = '2016-05-12'
)
AND S.type = 2;
WORKING DEMO
萬一你不能訪問SQL小提琴
-- ----------------------------
-- Table structure for `date-seat`
-- ----------------------------
DROP TABLE IF EXISTS `date-seat`;
CREATE TABLE `date-seat` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`date_booked` date NOT NULL,
`seat_id` int(11) NOT NULL,
`user_id` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of date-seat
-- ----------------------------
INSERT INTO `date-seat` VALUES ('1', '2016-05-12', '4', '2');
INSERT INTO `date-seat` VALUES ('2', '2016-05-14', '5', '3');
INSERT INTO `date-seat` VALUES ('3', '2016-05-14', '6', '5');
-- ----------------------------
-- Table structure for `seat`
-- ----------------------------
DROP TABLE IF EXISTS `seat`;
CREATE TABLE `seat` (
`seat_id` int(11) NOT NULL AUTO_INCREMENT,
`seat` int(11) NOT NULL,
`type` int(11) NOT NULL,
PRIMARY KEY (`seat_id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of seat
-- ----------------------------
INSERT INTO `seat` VALUES ('1', '1', '1');
INSERT INTO `seat` VALUES ('2', '2', '1');
INSERT INTO `seat` VALUES ('3', '3', '1');
INSERT INTO `seat` VALUES ('4', '7', '2');
INSERT INTO `seat` VALUES ('5', '8', '2');