2016-07-28 48 views
4

我有這兩列:從一個表中獲取兩個不同表格的輸入值

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。我要選擇除了7 2類型的所有席位,因爲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之外的所有座位。希望你能理解。

回答

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; 

WORKING DEMO

溶液#2(使用LEFT JOINIS 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'); 
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

嘗試此查詢:

SELECT * FROM date-seat ds 
RIGHT OUTER JOIN 
seat s ON ds.seat_id=s.seat_id 
WHERE 
    ds.seat_id IS NULL 

應用您的過濾器的其餘部分。

我希望你的rdbms支持外連接。

相關問題