选择的性能

bvjveswy  于 2021-06-21  发布在  Mysql
关注(0)|答案(1)|浏览(310)

我需要一些帮助来完成我的任务。我做了一个sql小提琴给你看数据库。
我需要执行两个查询,但它们没有正常工作:
第一:

SELECT  s.id, s.day_of_week, s.title
FROM slots s 
LEFT JOIN bookings_has_slots bhs
ON s.id = bhs.slot_id
LEFT JOIN bookings b
ON bhs.booking_id = b.id

WHERE NOT EXISTS (
  SELECT    null
  FROM  bookings_has_slots bhs2
  LEFT JOIN bookings b2
  ON        bhs2.booking_id = b2.id
  WHERE     b.date = '2018-01-27'
)
AND s.service_id = 3
AND s.day_of_week = DAYOFWEEK('2018-01-27');

退货:

id  day_of_week title
3   7           Après-midi (14h30 - 17h00)

但我希望:没有结果,因为这三个插槽的可能性,这一天的这一天,在同一天的一周。
第二:

SELECT DISTINCT b3.date AS unavailable_date
FROM bookings b3
LEFT JOIN bookings_has_slots bhs3
ON bhs3.booking_id = b3.id
LEFT JOIN slots s3
ON s3.id = bhs3.slot_id
WHERE NOT EXISTS (
  SELECT    null
  FROM slots s 
  LEFT JOIN bookings_has_slots bhs
  ON s.id = bhs.slot_id
  LEFT JOIN bookings b
  ON bhs.booking_id = b.id

  WHERE NOT EXISTS (
    SELECT  null
    FROM    bookings_has_slots bhs2
    LEFT JOIN bookings b2   
    ON      bhs2.booking_id = b2.id
    WHERE   b.date = b2.date
  )
  AND s.service_id = 3
  AND s.day_of_week = s3.day_of_week
);

退货:

unavailable_date
2018-01-17
2018-01-31
2018-01-27
2018-02-03

但我希望:

unavailable_date
2018-01-17
2018-01-31
2018-01-27

因为这里还有两个“2018-02-03”的空位,其他任何预订都没有。
下面是sql小提琴:
http://sqlfiddle.com/#!1989年9月46日
谢谢你的帮助。

ffvjumwh

ffvjumwh1#

这还不是答案。
但您能否确认这将解决您的第一个问题:

SELECT  s.id, s.day_of_week, s.title
FROM slots s 
LEFT JOIN (
  SELECT slot_id, booking_id
  FROM bookings_has_slots bhs
  INNER JOIN bookings b
  ON b.id = bhs.booking_id
    AND b.date = '2018-02-03'
  ) bhs
ON s.id = bhs.slot_id
WHERE s.day_of_week = DAYOFWEEK('2018-02-03')
  AND bhs.booking_id IS NULL;

第二个问题:
http://sqlfiddle.com/#!9/53a998/1号

SELECT d.date unavailable_date, d.used_slots
FROM (
  SELECT b.date, COUNT(b.id) used_slots
  FROM bookings b
  GROUP BY b.date
  ) d
LEFT JOIN slots s 
ON  s.day_of_week = DAYOFWEEK(d.date)
GROUP BY d.date
HAVING d.used_slots = COUNT(s.id);

相关问题