mysql group by 第一条,GROUP BY返回第一条记录

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

Is there any solution to GROUP BY the first record?

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

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 masterID for multi language table and suppose to return FIRST the records in currentLang and order them by name AND THEN all other languages.

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

So everything works fine so far expect the scenario that I have a record with languages en and fr. If currentLang is en then based on

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

the en order is 1 and fr order is 999 and instead of getting the value of en I get the value of fr.

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

解决方案

I assume you are talking of something like

SELECT *

FROM mytable

GROUP BY

column

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

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

)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值