MYSQL Select 来自相同 table 的不同记录

MYSQL Select different records from same table

我正在处理小型学校数据库,我需要一些帮助来选择仅在第 1 周和第 2 周的不同日期预订的学生。

我的 table 结构如下:

ChildId    Day  Room  Week
=======    ===  ====  ====
  1        1     20    1
  1        2     20    1
  2        1     20    2
  3        1     20    1
  3        2     20    1
  3        1     20    2
=====     ===   ===   ===

我想得到所有满足以下条件的children:

  SELECT DISTINCT b.childid FROM booking b
        where b.childid NOT IN (SELECT childid FROM bookingtemplate WHERE weekno = 1)

我也需要

我无法获得这两个星期的天数不同的 children:

谢谢

您可以使用聚合和 HAVING 子句中的条件来完成:

SELECT ChildId 
FROM booking
WHERE Week IN (1, 2)
GROUP BY ChildId
HAVING MIN(Week) = 2
    OR GROUP_CONCAT(DISTINCT CASE WHEN Week = 1 THEN Day END ORDER BY Day) <>
       GROUP_CONCAT(DISTINCT CASE WHEN Week = 2 THEN Day END ORDER BY Day);

参见demo

您可以自行加入 table 并过滤日期不同的情况。

SELECT DISTINCT
  b1.ChildId
FROM
  booking b1
INNER JOIN
  booking b2
ON
  b1.ChildId = v2.ChildId
  AND b1.Week = 1 AND b2.Week = 2
  AND b1.Day <> b2.Day