我有一个问题,如何使用最大(日期)输出“reading_timesent”的最新数据,并且还包括最新日期的其他列,并使用distinct或group删除冗余数据我不知道我的问题是这里的示例img和数据
患者表 阅读表 内部联接表 预期输出
SELECT * FROM Patients P
INNER JOIN Reading R ON R.patient_ID = P.patient_ID
答案 0 :(得分:2)
试试这个
SELECT * FROM
(
SELECT *,
(
SELECT reading_ID
FROM Reading
WHERE Reading.patient_ID = p.patient_ID
ORDER BY reading_timesent DESC
LIMIT 1
) AS newestReadingID
FROM Patients p
) AS subquery
JOIN Reading ON subquery.newestReadingID = Reading.reading_ID
答案 1 :(得分:2)
您可以在ON子句中使用相关子查询作为条件:
SELECT *
FROM Patients P
INNER JOIN Reading R
ON R.patient_ID = P.patient_ID
AND R.reading_timesent = (
SELECT MAX(R2.reading_timesent)
FROM Reading R2
WHERE R2.patient_ID = P.patient_ID
)
另一种方式:
SELECT P.*, R.*
FROM (
SELECT patient_ID, MAX(reading_timesent) as reading_timesent
FROM Reading
GROUP BY patient_ID
) X
JOIN Patients P USING (patient_ID)
JOIN Reading R USING (patient_ID, reading_timesent)
通常我会使用AUTO_INCREMENT列而不是TIMESTAMP列来执行类似的任务。但这并不总是适用。