search

Home  >  Q&A  >  body text

MySQL:此种查询结果,怎么仅保留第一条记录?

select id, value from test;
查询结果如下
id value
yy 123
zz 234
zz 456

仅想保留id字段的第一条记录,在5.7以下版本中使用"select id, value from test group by id"即可得到如下结果:
yy 123
zz 234

但在MySQL 5.7中该如何得到所需结果呢?该语句在5.7中非法

PHP中文网PHP中文网2837 days ago963

reply all(3)I'll reply

  • 黄舟

    黄舟2017-04-17 14:43:39

    Modify sql_mode in the MySQL configuration file and remove ONLY_FULL_GROUP_BY. If there is no sql_mode, add a line

    sql_model=

    reply
    0
  • PHPz

    PHPz2017-04-17 14:43:39

    SELECT id, value FROM (SELECT id, value FROM test ORDER BY id ) AS b GROUP BY id

    reply
    0
  • PHP中文网

    PHP中文网2017-04-17 14:43:39

    A digression:
    I am used to PostgreSQL and suddenly started using MySQL one day. I found that a non-key and non-aggregation-free SQL statement like the original poster can actually be established, and I was filled with fear.
    Later I discovered that MySQL didn’t even use the same window functions that are commonplace in PostgreSQL, and I was completely speechless.
    Okay, let’s provide something useful and implement the rank window function in MySQL:
    http://stackoverflow.com/questions/3333665/rank-function-in-mysql

    reply
    0
  • Cancelreply