是否可以在SELECT语句中计算日期范围?

时间:2013-06-23 19:31:59

标签: mysql sql database select range

我认为答案是肯定的,但是我的问题可能不太准确,不能用文字来形容我的真实含义,所以我想出了一个相当愚蠢的例子来说明我想要问的问题

假设佩戴者必须连续戴帽子,每当它改变帽子时,它必须记录新的帽子的日期和名称。

使用下面的三个表格,当发件人做出赞美时,是否可以告诉(SELECT)接收者佩戴的帽子?我试图避免在 Compliment 表中使用 Hat 的PK放置第六列。

我想获得一行作为回报,而不是所有的帽子的日期大于赞美的日期。

enter image description here

2 个答案:

答案 0 :(得分:2)

如果我理解你的问题,我认为你正在寻找这个:

SELECT
  c.id,
  c.sender,
  c.receiver,
  c.compliment,
  c.date,
  h.hat
FROM (
  SELECT
    compliment.id,
    compliment.sender,
    compliment.receiver,
    compliment.compliment,
    compliment.date,
    max(hat.date) mx
  FROM
    compliment INNER JOIN hat
    ON compliment.receiver = hat.wearer AND compliment.date>=hat.date
  GROUP BY
    compliment.id,
    compliment.sender,
    compliment.receiver,
    compliment.compliment,
    compliment.date) c
  LEFT JOIN hat h
  ON c.receiver = h.wearer AND h.date=c.mx

请参阅小提琴here

修改

更清洁的版本可以写成:

SELECT
  compliment.*,
  hat.hat
FROM (
  SELECT
    compliment.id,
    receiver,
    max(hat.date) mx
  FROM
    compliment LEFT JOIN hat
    ON compliment.receiver = hat.wearer
       AND compliment.date >= hat.date
  GROUP BY
    compliment.id,
    compliment.receiver
  ) max_date
  INNER JOIN compliment ON max_date.id=compliment.ID
  LEFT JOIN hat ON max_date.mx = hat.date AND max_date.receiver=hat.wearer

答案 1 :(得分:2)

我认为最简单的公式是嵌套的select语句:

select c.*,
       (select h.hat
        from hat h
        where h.wearer = c.receiver and
              h.date <= c.date
        order by date desc
        limit 1
       ) as hat
from compliment c;

嵌套选择不是我最喜欢的SQL构造。但这恰好是他们非常有效地捕获逻辑的情况。

出于性能原因,我建议在hat(wearer, date)上建一个索引。