PostgreSQL技术问询:查询指定ID对应最高C4版本的所有行
Hey there! Let's figure out how to get those highest-version rows for your specific ID in PostgreSQL. Since you're new to Postgres, I'll break down a few straightforward, effective approaches tailored to your table structure:
方法1:使用窗口函数(推荐,灵活通用)
窗口函数 is the go-to solution for "get top N rows per group" problems. We can use ROW_NUMBER() or RANK() to mark the version order for each ID, then filter out the highest version rows:
-- Use this if there's only one row with the highest C4 for your target ID SELECT t.* FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY ID ORDER BY C4 DESC) AS rn FROM T WHERE ID = 'your-target-id' -- Replace with your actual ID value ) t WHERE t.rn = 1;
If multiple rows might share the highest C4 version for the same ID (like inserting multiple records in one version update), use RANK() instead—it will keep all those rows instead of picking just one:
SELECT t.* FROM ( SELECT *, RANK() OVER (PARTITION BY ID ORDER BY C4 DESC) AS rnk FROM T WHERE ID = 'your-target-id' ) t WHERE t.rnk = 1;
方法2:子查询 + 关联(直观易懂)
First find the maximum C4 value for your target ID, then match that value back to the original table. This logic is super easy to follow:
SELECT * FROM T WHERE ID = 'your-target-id' AND C4 = (SELECT MAX(C4) FROM T WHERE ID = 'your-target-id');
方法3:PostgreSQL特有的DISTINCT ON(简洁高效)
Postgres has a unique syntax DISTINCT ON that lets you quickly grab the first row of each group. Pair it with sorting to get the highest version directly:
SELECT DISTINCT ON (ID) * FROM T WHERE ID = 'your-target-id' ORDER BY ID, C4 DESC;
Quick tip:
DISTINCT ONrequires the firstORDER BYfield to match the grouping field (here it'sID). If there are multiple rows with the highest C4, this will return the first one in the sorted order—you can add extra fields (like C1 or C2) to theORDER BYto control which row gets picked.
内容的提问来源于stack exchange,提问作者DJ_Stuffy_K

