问题描述
我正在使用mySQL构建一个应用程序,客户可以在其中选择可用日期。
我想要两个查询,一个查询指定每个客户选择的时段,另一个查询指定尚未选择的日期。
设置
我有一个以日期形式的时隙列表
TABLE: timeslots
slot_id | date
1 | 2020-10-01
2 | 2020-10-02
3 | 2020-10-03
我也有一个客户表
TABLE: customers
customer_id | name
1 | Anders
2 | Joe
3 | Karen
每个客户都可以选择customer_timeslot表中指定的任意日期,该表具有两个外键。
TABLE: customer_timeslot
customer_id | slot_id
1 | 1
1 | 2
2 | 1
3 | 1
第一个查询都很好
第一个查询很容易,并且给了我安德斯选择的日期。
查询Anders(客户1)选择的日期
SELECT timeslots.date AS Date,customer.name AS Customer FROM timeslots
JOIN customer_timeslot
USING (slot_id)
JOIN customers
USING (customer_id)
WHERE customers.customer_id = 1
结果查询1
Date | Customer
2020-10-01 | Anders
2020-10-02 | Anders
我想要第二个查询的结果
我希望Anders尚未选择像这样的日期
Date | Customer
2020-10-03 | Anders
我尝试过的事情
我尝试使用LEFT JOIN代替JOIN。
SELECT timeslots.date AS Date,customer.name AS Customer FROM timeslots
LEFT JOIN customer_timeslot
USING (slot_id)
JOIN customers
USING (customer_id)
WHERE customers.customer_id = 1
..我期望这会给我这个结果,但是却给了我与INNER JOIN完全相同的信息(不使用NULL)
Date | Customer
2020-10-01 | Anders
2020-10-02 | Anders
2020-10-03 | NULL
如何获得所需的查询?我想应该没有那么复杂,但是我发现自己完全陷入了困境,正在寻找帮助。
解决方法
您可以使用not exists
:
select t.*
from timeslots t
where not exists (
select 1
from customer_timeslot ct
where ct.customer_id = 1 and ct.slot_id = t.slot_id
)
这将返回customer_id
1
未选择的时隙。您可以先使用cross join
,然后使用not exists
来获取所有客户的信息:
select t.date,c.name
from timeslots t
cross join customers c
where not exists (
select 1
from customer_timeslot ct
where ct.customer_id = c.customer_id and ct.slot_id = t.slot_id
)