【问题标题】:MySQL Query for dates that have not been picked by a customerMySQL 查询客户尚未选择的日期
【发布时间】:2021-01-30 19:21:01
【问题描述】:

我正在使用 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 (cust. 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

第二个查询我想要的结果

我想要安德斯尚未选择的日期,看起来像这样

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

如何获得所需的查询?我想不应该那么复杂,但我发现自己完全陷入困境并寻求帮助。

【问题讨论】:

    标签: mysql sql subquery cross-join


    【解决方案1】:

    你可以使用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 joinnot 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
    )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-03-02
      • 1970-01-01
      • 2011-11-07
      • 1970-01-01
      • 1970-01-01
      • 2012-05-25
      相关资源
      最近更新 更多