我使用MySQL数据库管理组织的捐款。捐赠者可以捐赠多份捐款。因此,我有两个表:donators
包含有关捐赠者的信息,donations
包含有关捐赠时间和金额的信息。两个表都通过donatorID
连接。
我想读出有关每个不同捐赠者的信息。该清单应按上次捐赠日期排序。我想出了下面的代码,但是它使用了第一次捐赠的日期而不是最后一次捐赠。
如何为每位捐赠者使用最新的捐赠日期?
SELECT
DISTINCT(`donators`.`name`),
`donators`.`city`,
`donators`.`country`,
`donators`.`website`
FROM
`donators`
INNER JOIN
`donations`
ON
`donators`.`donatorID` = `donations`.`donatorID`
ORDER BY `donations`.`date` DESC
答案 0 :(得分:5)
SELECT a.*, b.max_DATE
FROM Donators a
INNER JOIN
(
SELECT DonatorID, MAX(date) max_DATE
FROM Donations
GROUP BY DonatorID
) b ON a.DonatorID = b.DonatorID
ORDER BY b.max_DATE DESC
如果您想根据最新的捐赠日期显示donation
表的记录,
SELECT a.*, c.*
FROM Donators a
INNER JOIN Donations c
ON a.DonatorID = c.DonatorID
INNER JOIN
(
SELECT DonatorID, MAX(date) max_DATE
FROM Donations
GROUP BY DonatorID
) b ON c.DonatorID = b.DonatorID AND
c.date = b.max_DATE
ORDER BY c.date DESC
答案 1 :(得分:1)
假设您对donations
表中的各个值不感兴趣,可以使用此查询:
SELECT
`donators`.`name`,
`donators`.`city`,
`donators`.`country`,
`donators`.`website`,
MAX(`donations`.`date`) AS LastDate
FROM `donators`
INNER JOIN `donations` ON `donators`.`donatorID` = `donations`.`donatorID`
GROUP BY
`donators`.`name`,
`donators`.`city`,
`donators`.`country`,
`donators`.`website`
ORDER BY
LastDate DESC
答案 2 :(得分:1)
SELECT
who.name
, who.city
, who.country
, who.website
, what.thedate
FROM donators who
JOIN donations what ON what.donatorID = who.donatorID
WHERE NOT EXISTS (
SELECT *
FROM donations nx
WHERE nx.donatorID = what.donatorID
AND nx.thedate > what.thedate
)
ORDER BY what.thedate DESC
;