在MySQL中,我只有一个名为约会主机的表,用于存储患者输入的预订日期和时间。预约时间是固定的,这意味着患者可以每10分钟预约一次,这意味着如果一个患者在10:00 AM进行了预约,那么其他患者可以在10:10 AM进行预约,依此类推。现在,如果在上午10:00预约约会,并且当其他患者尝试预约时,日期和时间段选项10:00 AM不应在表单选择选项标签中显示给其他患者。

我的表如下:

name   lastname age gender   email            phone_no   app_date    app_time
ramesh  ahir    30  Male    [email protected]   9824758745 2019-01-18  10:20:00
jitesh  thacker 35  Male    [email protected]  9824758745 2019-01-21  10:30:00

最佳答案

考虑以下非常简化的示例:

DROP TABLE IF EXISTS slots;

CREATE TABLE slots
(id SERIAL PRIMARY KEY,slot VARCHAR(12) NOT NULL UNIQUE);;

INSERT INTO slots VALUES
(1,'Slot 1'),
(2,'Slot 2'),
(3,'Slot 3'),
(4,'Slot 4'),
(5,'Slot 5');

DROP TABLE IF EXISTS bookings;

CREATE TABLE bookings
(booking_id SERIAL PRIMARY KEY
,user_id INT  NOT NULL
,slot_id INT NOT NULL UNIQUE
);

INSERT INTO bookings VALUES
(1,101,3);


为了显示可用的广告位,我们可以执行以下操作...

SELECT s.*
  FROM slots s
  LEFT
  JOIN bookings b
    ON b.slot_id = s.id
 WHERE b.booking_id IS NULL;
+----+--------+
| id | slot   |
+----+--------+
|  1 | Slot 1 |
|  2 | Slot 2 |
|  4 | Slot 4 |
|  5 | Slot 5 |
+----+--------+


...或这个...

SELECT s.*
     , CASE WHEN b.booking_id IS NULL THEN 'yes' ELSE 'no' END available
  FROM slots s
  LEFT
  JOIN bookings b
    ON b.slot_id = s.id;
+----+--------+-----------+
| id | slot   | available |
+----+--------+-----------+
|  1 | Slot 1 | yes       |
|  2 | Slot 2 | yes       |
|  3 | Slot 3 | no        |
|  4 | Slot 4 | yes       |
|  5 | Slot 5 | yes       |
+----+--------+-----------+


为了确保两个用户不能同时预订同一个广告位,我们可以执行以下操作...

INSERT INTO bookings (user_id,slot_id)
SELECT 102,1
  FROM (SELECT 1) x
  LEFT
  JOIN bookings y
    ON y.slot_id = 1
 WHERE y.booking_id IS NULL;

SELECT * FROM bookings;
+------------+---------+---------+
| booking_id | user_id | slot_id |
+------------+---------+---------+
|          1 |     101 |       3 |
|          2 |     102 |       1 |
+------------+---------+---------+


...这可以防止其他用户预订相同的广告位...

INSERT INTO bookings (user_id,slot_id)
SELECT 103,1
  FROM (SELECT 1) x
  LEFT
  JOIN bookings y
    ON y.slot_id = 1
 WHERE y.booking_id IS NULL;

SELECT * FROM bookings;
+------------+---------+---------+
| booking_id | user_id | slot_id |
+------------+---------+---------+
|          1 |     101 |       3 |
|          2 |     102 |       1 |
+------------+---------+---------+


其他所有内容都可以在您的应用程序代码(PHP)中处理。

08-17 02:45