You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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:

  1. Add language grouping logic: The join condition now ensures we only compare rows within the same title AND same language (including cases where both have NULL for language—since NULL = NULL returns false, we explicitly check for that scenario).
  2. Keep the "no larger value" check: The t1.value < t2.value condition still finds rows where there's no other row in the same group with a higher value (your "latest value" requirement).
  3. Use unique id for null check: Replaced t2.title IS NULL with t2.id IS NULL for accuracy, since id is 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 have language NULL): We keep the row with value = 1900 (no other row in the group has a higher value).
  • For title = 'b': We split into two groups—language NULL (keep value = 1750) and language = 1 (only one row, so it's retained).
  • For title = 'c': Each language group 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 07:51:35