Mysql补充了许多表和分组

时间:2012-07-29 12:50:21

标签: mysql complement

我希望答案很简单,我很傻。

所以我有两张表:day(PK id_day)和hour(PK id_hour)。

我还有另一个表tilt_time,其中包含id_dayid_hour字段和一个加FK字段(具有禁止时间)。例如。 tilt_time包含以下行(id_dayid_hourid_target):

1,1,1
1,2,1
1,3,1
1,1,2
1,2,2

day id_day介于1到5之间(星期一至星期五),hour id_hour介于1到6之间(因此您可以设想{{1}表格,5 * 6 = 30个值)。

所以我想要查询day_hour的空闲时段和id_target=1的空闲时段(永远的自由时段)。所以我想要类似的:

id_target=2

(*表示所有有效的1,4,1 1,5,1 1,6,1 2,*,1 3,*,1 4,*,1 5,*,1 // id_target=2 1,3,2 1,4,2 1,5,2 1,6,2 2,*,2 3,*,2 4,*,2 5,*,2 值,因此带*的每一行代表6条不同的行)

我该如何进行此查询?

2 个答案:

答案 0 :(得分:0)

如果您的target表格中包含所有id_target,则答案很简单:

SELECT 
    d.id_day, h.id_hour, t.id_target
FROM 
    day AS d
  CROSS JOIN
    hour AS h
  CROSS JOIN
    target AS t
WHERE
    (d.id_day, h.id_hour, t.id_target) NOT IN
      ( SELECT id_day, id_hour, id_target
        FROM tilt_time
      )
;

或(可能更有效率):

SELECT 
    d.id_day, h.id_hour, t.id_target
FROM 
    day AS d
  CROSS JOIN
    hour AS h
  CROSS JOIN
    target AS t
  LEFT JOIN
    tilt_time AS tt
      ON  tt.id         = d.id_day
      AND tt.id_hour    = h.id_hour
      AND t.t.id_target = t.id_target
WHERE 
    tt.id_target iS NULL ;

如果您没有target表,请将以上代码中的target AS t替换为:

( SELECT DISTINCT id_target FROM tilt_time ) AS t

答案 1 :(得分:0)

以下查询返回id_dayid_hour,其中目标ID 1和2在tilt_time中都没有记录。

SELECT tg1_free.id_day, tg2_free.id_hour
FROM (
    SELECT
        day.id_day, hour.id_hour
    FROM day, hour
    WHERE
        (day.id_day, hour.id_hour) NOT IN (SELECT id_day, id_hour FROM tilt_time WHERE id_target = 1)
) tg1_free
INNER JOIN (
    SELECT
        day.id_day, hour.id_hour
    FROM day, hour
    WHERE
        (day.id_day, hour.id_hour) NOT IN (SELECT id_day, id_hour FROM tilt_time WHERE id_target = 2)
) tg2_free ON (tg1_free.id_day = tg2_free.id_day AND tg1_free.id_hour = tg2_free.id_hour)

[编辑]

对于所有目标ID,都有(甚至更容易):

SELECT id_day, id_hour
FROM day, hour
WHERE
    (day.id_day, hour.id_hour) NOT IN (SELECT id_day, id_hour FROM tilt_time);