来自连接查询的最新内容

时间:2014-07-09 12:18:42

标签: sql postgresql

CREATE TABLE asset (
  asset_name VARCHAR(255) NOT NULL PRIMARY KEY
);

CREATE TABLE asset_purchase (
  asset_name         VARCHAR(255) REFERENCES asset,
  purchase_value     INT NOT NULL,
  purhcase_timestamp INT NOT NULL
);
  1. 系统中有大约100个资产。
  2. 每项资产都有很多购买。
  3. 我想获得最新购买的每项资产
  4. 我尝试以下查询:

    SELECT * 
    FROM 
    asset 
    JOIN asset_purchase USING (asset_name) ORDER BY purhcase_timestamp LIMIT 1;
    

    但它只返回一个条目

1 个答案:

答案 0 :(得分:1)

SELECT  *
FROM    (
        SELECT  ap.*,
                ROW_NUMBER() OVER (PARTITION BY a.asset_name ORDER BY purchase_timestamp DESC) rn
        FROM    asset a
        LEFT JOIN
                asset_purchase ap
        ON      ap.asset_name = a.asset_name
        ) q
WHERE   rn = 1

,或

SELECT  (a).*, (ap).*
FROM    (
        SELECT  asset.a,
                (
                SELECT  ap
                FROM    asset_purchase ap
                WHERE   ap.asset_name = a.asset_name
                ORDER BY
                        purchase_timestamp DESC
                LIMIT 1
                )
         ) q

,或

SELECT  DISTINCT ON (a.asset_name)
        *
FROM    asset a
LEFT JOIN
        asset_purchase ap
ON      ap.asset_name = a.asset_name
ORDER BY
        a.asset_name, ap.purchase_timestamp DESC

,或(在PostgreSQL 9.3 +中)

SELECT  *
FROM    asset
LEFT JOIN
        LATERAL
        (
        SELECT  *
        FROM    asset_purchase ap
        WHERE   ap.asset_name = a.asset_name
        ORDER BY
                purchase_timestamp DESC
        LIMIT 1
        ) ap
ON      TRUE