如何基于Name字段最大长度从关联结果中筛选单条匹配记录
Got it, let's break down how to solve this problem. The goal is to take your existing join between ShortNames and LongNames, then for each matching group (tied to a record in LongNames), only keep the entry from ShortNames with the longest Name value.
Method 1: Using Window Functions (Modern Databases like MySQL 8.0+, PostgreSQL, etc.)
This is the cleanest and most efficient approach if your database supports window functions. We'll use ROW_NUMBER() to rank matches by the length of T1.Name in descending order, then pick the top-ranked entry for each LongNames record.
WITH ranked_matches AS ( SELECT T1.ID, T1.Name, -- Include T2 fields if you need them, e.g., T2.Name AS Long_Name CHAR_LENGTH(T1.Name) AS name_length, ROW_NUMBER() OVER ( PARTITION BY T2.ID ORDER BY CHAR_LENGTH(T1.Name) DESC ) AS rank_num FROM ShortNames T1 INNER JOIN LongNames T2 ON T2.Name LIKE CONCAT('% ', T1.Name) OR T2.Name LIKE CONCAT(T1.Name, ' %') ) SELECT ID, Name FROM ranked_matches WHERE rank_num = 1;
- How it works:
- The CTE (
ranked_matches) first runs your original join and calculates the length of eachT1.Name. ROW_NUMBER()assigns a unique rank to each match within the sameLongNamesrecord (PARTITION BY T2.ID), with the longest name getting rank 1.- We filter for
rank_num = 1to get only the longest name perLongNamesentry.
- The CTE (
Note: If there are multiple ShortNames entries with the same maximum length and you want to keep all of them, replace ROW_NUMBER() with RANK().
Method 2: Subquery Approach (Compatible with Older Databases)
If you're working with an older database that doesn't support CTEs or window functions, you can use a subquery to first find the maximum name length for each LongNames record, then join back to get the corresponding ShortNames entry.
SELECT T1.ID, T1.Name FROM ShortNames T1 INNER JOIN LongNames T2 ON T2.Name LIKE CONCAT('% ', T1.Name) OR T2.Name LIKE CONCAT(T1.Name, ' %') INNER JOIN ( SELECT T2.ID AS long_id, MAX(CHAR_LENGTH(T1.Name)) AS max_name_length FROM ShortNames T1 INNER JOIN LongNames T2 ON T2.Name LIKE CONCAT('% ', T1.Name) OR T2.Name LIKE CONCAT(T1.Name, ' %') GROUP BY T2.ID ) AS max_lengths ON T2.ID = max_lengths.long_id AND CHAR_LENGTH(T1.Name) = max_lengths.max_name_length;
- How it works:
- The subquery
max_lengthscalculates the longestShortNamesname length for eachLongNamesrecord. - We join this subquery back to the original join results to filter only the entries where the name length matches the maximum for that
LongNamesrecord.
- The subquery
内容的提问来源于stack exchange,提问作者Mark H

