MySQL GROUP BY 返回第一条记录

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2362720/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 15:25:04  来源:igfitidea点击:

GROUP BY return the first record

mysqlgroup-by

提问by ntan

As far as I know mysql GROUP BY groups to the last record found.

据我所知 mysql GROUP BY 组找到的最后一条记录。

Is there any solution to GROUP BY the first record?

GROUP BY第一条记录有什么解决办法吗?

I have setup the ORDER in SQL command and I need GROUP BY return the first record and not the last.

我已经在 SQL 命令中设置了 ORDER,我需要 GROUP BY 返回第一条记录而不是最后一条记录。

EDIT

编辑

Here is the Query

这是查询

SELECT 
  DISTINCT(master.masterID),
  langData.*,
  master.* 
FROM master_table as master 
INNER JOIN lang_table as langData ON 
langData.masterID=master.masterID 
GROUP BY master.masterID 
ORDER BY 
CASE 
    WHEN langData.lang='currentLang' THEN 1 ELSE 999 END , 
    master.name desc LIMIT 0,10 

The query above select the masterIDfor multi language table and suppose to return FIRST the records in currentLangand order them by name AND THEN all other languages.

上面的查询选择了masterID多语言表,并假设首先返回记录currentLang并按名称排序,然后是所有其他语言。

Don't ask me why I don't set the language in JOIN. This is the way to be done.

不要问我为什么不在JOIN里设置语言。这是要完成的方法。

So everything works fine so far expect the scenario that I have a record with languages enand fr. If currentLangis enthen based on

所以到目前为止一切正常,期待我有语言enfr. 如果currentLangen再依据

langData.lang='currentLang' THEN 1 ELSE 999 END

the enorder is 1 and frorder is 999 and instead of getting the value of enI get the value of fr.

en订单是1和fr秩序是和999不是获取价值的en,我得到的价值fr

That's why I want to group to the first row.

这就是为什么我想分组到第一行。

采纳答案by Quassnoi

I assume you are talking of something like

我假设你在谈论类似的事情

SELECT  *
FROM    mytable
GROUP BY
        column

You shouldn't use unaggregated expressions in GROUP BYunless they are all same within the group.

GROUP BY除非它们在组内都相同,否则不应在其中使用未聚合的表达式。

If you want to return the record holding the least value of an expression within a group, use this:

如果要返回组中包含表达式最小值的记录,请使用以下命令:

SELECT  mo.*
FROM    (
        SELECT  DISTINCT column
        FROM    mytable
        ) md
JOIN    mytable mo
ON      mo.id = 
        (
        SELECT  id
        FROM    mytable mi
        WHERE   mi.column = md.column
        ORDER BY
                mi.column, mi.someorder
        LIMIT 1
        )

回答by Daniel A. White

Add LIMIT 1to your query.

添加LIMIT 1到您的查询中。