0

我使用 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
4

3 回答 3

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  
于 2013-01-19T12:53:29.420 回答
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
于 2013-01-19T12:56:55.460 回答
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
        ;
于 2013-01-19T13:10:29.260 回答