0

組織への寄付を管理するために MySQL データベースを使用しています。寄付者は複数の寄付を行うことができます。donatorsしたがって、寄付者に関する情報と、寄付donationsの時間と金額に関する情報を含む2 つのテーブルがあります。両方のテーブルが を介して接続されてい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 に答える