我认为答案是肯定的,但是我的问题可能不太准确,不能完全用文字来描述我的真正意思,所以我想出了一个相当愚蠢的例子来说明我想问的问题。
假设佩戴者必须连续戴帽子,并且每次更换帽子时都必须记录新帽子的日期和名称。
使用下面的三个表格,当发送者称赞时,是否可以告诉(SELECT)
接收者戴的帽子?我试图避免在Compliment表中使用Hat PK放置第六列。
我想得到一排作为回报,而不是所有日期大于赞美日期的帽子。
如果我正确理解您的问题,我认为您正在寻找这个:
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
请在此处查看小提琴。
编辑
更简洁的版本可以这样写:
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
我认为最简单的表述是嵌套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)
.