我有这两列:
1. seat
已经填满了。 seat_id是auto_increment。
seat_id seat type
1 1 1
2 2 1
3 3 1
4 7 2
.. .. ..
2。 date-seat
id date_booked seat_id user_id
1 2016-5-12 4 2
2 2016-5-14 5 3
.. .. .. ..
我想从给定类型和给定日期中选择座位。例如,如果类型是2,日期是2016-5-12。我想选择所有类型2的座位,除了7.因为seat_id 4,即座位7已经在2016-5-12日期在那里
我尝试了什么:
$type=$_POST['type'];
$flightdate=$_POST['flightdate'];
$sql ="SELECT seat, seat_id FROM seat INNER JOIN `date-seat` ON seat.seat_id=`date-seat`.seat_id WHERE `date-seat`.date_booked<>$flightdate AND seat.type=$type";
这个sql给了我在date_booked中不匹配的席位。即如果我选择类型2和日期2016-5-12。它只给出seat_id 5的座位。但是我想要除seat_id之外的所有座位4.希望你理解。
答案 0 :(得分:1)
有几种不同的方法可以做到这一点。这是not exists
的一个:
select *
from seat s
where not exists (
select 1
from dateseat ds
where ds.date_booked = '2016-5-12' and ds.seat_id = s.seat_id
)
答案 1 :(得分:1)
尝试此查询:
SELECT * FROM date-seat ds
RIGHT OUTER JOIN
seat s ON ds.seat_id=s.seat_id
WHERE
ds.seat_id IS NULL
应用其余的过滤器。
我希望你的rdbms支持外连接。
答案 2 :(得分:1)
解决方案#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;
解决方案#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;
解决方案#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;
万一你无法访问 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');