MySQL多列筛选最大行:基于title和language且避免聚合函数
Solution: Filter Rows by Title + Language Groups Without Aggregate Functions
Got it, let's work through this together. Your original query only considers grouping by title, but we need to extend it to include the language dimension—including handling NULL values for language, since NULL doesn't match itself in standard SQL joins.
Here's the modified query that meets your requirements:
SELECT t1.* FROM your_table t1 LEFT OUTER JOIN your_table t2 ON t1.title = t2.title AND ( (t1.language IS NULL AND t2.language IS NULL) OR t1.language = t2.language ) AND t1.value < t2.value WHERE t2.id IS NULL;
Breakdown of the changes:
- Add language grouping logic: The join condition now ensures we only compare rows within the same
titleAND samelanguage(including cases where both haveNULLfor language—sinceNULL = NULLreturns false, we explicitly check for that scenario). - Keep the "no larger value" check: The
t1.value < t2.valuecondition still finds rows where there's no other row in the same group with a highervalue(your "latest value" requirement). - Use unique id for null check: Replaced
t2.title IS NULLwitht2.id IS NULLfor accuracy, sinceidis a unique identifier and guarantees we're targeting rows with no matching larger-value row.
Why this works for your expected output:
- For
title = 'a'(both rows havelanguage NULL): We keep the row withvalue = 1900(no other row in the group has a higher value). - For
title = 'b': We split into two groups—language NULL(keepvalue = 1750) andlanguage = 1(only one row, so it's retained). - For
title = 'c': Eachlanguagegroup has only one row, so all are kept. - For
title = 'd': Only one row exists, so it's retained.
This query avoids all aggregate functions, so when you create a view with it, MySQL will use the MERGE algorithm (no temporary tables created), just as you need.
内容的提问来源于stack exchange,提问作者John Miller
相关产品推荐
相关产品推荐

