在一个查询中检查多个表

时间:2019-01-18 04:35:20

标签: php mysql join select pdo

我想使用PHP从我的MySQL SELECT中获取数据,但是WHERE子句可能会造成混淆。

基本上,我想选择即将到来的约会,然后检查企业是否要发送提醒,然后检查用户是否要接收提醒。但我想在一个查询中完成所有操作。

这是我的桌子:

appointments
    - appointment_date
    - appointment_time
    - business_id
    - user_id

businesses
    - reminders_enabled

users
    - reminders_enabled

在选择正确的数据之前,这是我要执行的步骤:

  1. SELECT * FROM appointments WHERE DATE(appointment_date) = CURDATE() AND appointment_time is within the next 1 hour

  2. 从上面从步骤1中选择的数据中,我要对其进行过滤。我想SELECT * FROM businesses WHERE business_id = business_id_from_step_1 AND reminders_enabled = 1

  3. 然后我想进一步过滤它。如果在第2步之后找到结果,请再次选择:SELECT * FROM users WHERE user_id = user_id_from_step_1 AND reminders_enabled = 1

就是这样。我怎样才能做到这一点?谢谢!

2 个答案:

答案 0 :(得分:1)

类似的事情应该起作用。 JOIN会按照步骤1-3中的描述进行过滤:

SELECT *
FROM appointments a
JOIN businesses b ON b.business_id = a.business_id AND b.reminders_enabled = 1
JOIN users u ON u.user_id = a.user_id AND u.reminders_enabled = 1
WHERE DATE(a.appointment_date) = CURDATE() AND 
      a.appointment_time BETWEEN NOW() AND NOW() + INTERVAL 1 HOUR

答案 1 :(得分:1)

SELECT * FROM appointments 
      WHERE DATE(appointment_date) = CURDATE()
      AND appointment_time BETWEEN NOW() AND NOW() + INTERVAL 1 HOUR
      AND business_id in (SELECT business_id FROM businesses WHERE reminders_enabled=1)
      AND user_id in (SELECT user_id FROM users WHERE reminders_enabled=1)