GROUP BY在SQL中选择哪条记录 [英] Which record will GROUP BY choose in SQL

查看:238
本文介绍了GROUP BY在SQL中选择哪条记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样一个SQL查询:

  SELECT playerno,town 
FROM players
GROUP BY城镇

在这种情况下,服务器会返回让我们说一个城镇,而对于playerno,它会返回一个值,即使数据库中有多个值。



我的问题是,将选择哪个值?选择是随机的,还是会取得第一个结果,还是会发生其他事情?
谢谢。

解决方案

如果您不告诉引擎要做什么,它会自行决定。它取决于引擎一些将采取第一个,其他人将采取最后一个,并有一些错误。您可以使用以下功能之一来控制此功能:


  1. first(fieldname)

  2. last (字段名称)

  3. 分钟(字段名称)

  4. max(字段名称)

  5. b

    或者甚至采取一种估价或总和:通过使用su


    If I have an SQL query like this one:

    SELECT playerno,town
    FROM players
    GROUP BY town
    

    In this case, the server will return lets say one town, and for playerno, it will return one value, even if there were multiple values in the database.

    My question is, which value will be chosen? Is the choice made randomly, or will it take the first result, or something else will happen? Thank you.

    解决方案

    If you don't tell the engine what to do , it decides for itself. Its depending on the engine some will take the first one, others will take the last one, and some give an error. You can control this by using one of those functions:

    1. first(fieldname)
    2. last(fieldname)
    3. min(fieldname)
    4. max(fieldname

    or even take an avarge or sum: by using su

    这篇关于GROUP BY在SQL中选择哪条记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆