我正在尝试编写一个从四个表中获取信息的查询,但我无法弄清楚。有人可以帮我一些指导吗?
该模型是用户可以在指定的时间段内预订房间。我想检索未来 7 天的最新数据,因此我使用的是 WEEK 和 DATEDIFF。DATEDIFF 是为了确保我不会取回未来或一年多以前发生的任何房间预订。我有四张表:用户、房间、时间、预订
用户:
CREATE TABLE IF NOT EXISTS users (
apartmentNumber varchar(4) NOT NULL,
surname varchar(50) NOT NULL,
password varchar(40) NOT NULL,
PRIMARY KEY (apartmentNumber)
)
房间:
CREATE TABLE IF NOT EXISTS rooms (
id int(11) NOT NULL auto_increment,
name varchar(40) NOT NULL,
PRIMARY KEY (id),
KEY name (name)
)
时间:
CREATE TABLE IF NOT EXISTS times (
id int(11) NOT NULL auto_increment,
start time NOT NULL,
stop time NOT NULL,
PRIMARY KEY (id),
KEY start (start)
)
预订:
CREATE TABLE IF NOT EXISTS bookings (
id int(11) NOT NULL auto_increment,
user varchar(4) NOT NULL,
room int(11) NOT NULL,
date date NOT NULL,
time int(11) NOT NULL,
PRIMARY KEY (id),
KEY room (room),
KEY time (time),
KEY user (user)
)
我用以下数据填充了这些表:
INSERT INTO bookings (id, user, room, date, time) VALUES
(1, '0379', 1, '2009-11-19', 1),
(2, '0379', 1, '2009-11-23', 2),
(3, '0379', 1, '2009-11-14', 3),
(4, '0379', 2, '2009-11-23', 3),
(5, '0379', 2, '2009-11-19', 2),
(6, '0379', 2, '2009-11-20', 1);
ALTER TABLE bookings
ADD CONSTRAINT bookings_ibfk_2 FOREIGN KEY (room) REFERENCES rooms (id) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT bookings_ibfk_3 FOREIGN KEY (user) REFERENCES users (apartmentNumber) ON DELETE CASCADE ON UPDATE CASCADE,
ADD CONSTRAINT bookings_ibfk_4 FOREIGN KEY (time) REFERENCES times (id) ON DELETE CASCADE ON UPDATE CASCADE;
INSERT INTO rooms (id, name) VALUES
(1, 'Room 1'),
(2, 'Room 2');
INSERT INTO times (id, start, stop) VALUES
(1, '07:00:00', '12:00:00'),
(2, '12:00:00', '17:00:00'),
(3, '17:00:00', '22:00:00');
INSERT INTO users (apartmentNumber, surname, password) VALUES
('0379', 'Smith', 'password');
在添加时间表之前(因为时间以前在预订表中),我设法通过以下查询获取数据:
SELECT users.surname, users.apartmentNumber, rooms.name as room, bookings.date, bookings.time
FROM bookings, rooms, users
WHERE WEEK(NOW(), 7) = WEEK(bookings.date, 7)
AND DATEDIFF(NOW(), bookings.date) < 1
AND DATEDIFF(NOW(), bookings.date) > -10
AND users.apartmentNumber = bookings.user
AND bookings.room = rooms.id
ORDER BY room, bookings.time, bookings.date ASC;
但是在将时间划分到单独的表格之后,我无法做到:
SELECT users.surname, users.apartmentNumber, rooms.name as room, bookings.date, times.start, times.stop
FROM bookings, rooms, users, times
WHERE WEEK(NOW(), 7) = WEEK(bookings.date, 7)
AND DATEDIFF(NOW(), bookings.date) < 1
AND DATEDIFF(NOW(), bookings.date) > -10
AND users.apartmentNumber = bookings.user
AND bookings.room = rooms.id
AND times.id = bookings.time
ORDER BY room, bookings.time, bookings.date ASC;
上述查询的结果集是:
Smith 379 Room 2 2009-11-20 07:00:00 12:00:00
但它应该包括 2009-11-23 的两次预订
我迷路了......任何评论将不胜感激。谢谢!
/安德斯