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
);
我尝试以下查询:
SELECT *
FROM
asset
JOIN asset_purchase USING (asset_name) ORDER BY purhcase_timestamp LIMIT 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