首页 > 解决方案 > 在 MySQL 5 中将 Limit 与 group_contact 一起使用

问题描述

大家早上好,我有一个问题:

我有以下示例 SQL:

group_concat( DISTINCT `mvu5877_anuncios_photos`.`image` ORDER BY `mvu5877_anuncios_photos`.`order` ASC SEPARATOR ',' ) AS `images`

在 SEPARATOR 中,我需要定义一个数量而不是带上所有项目。在 MariaDB 中,我可以在最后超过限制时做到这一点。例子:

group_concat( DISTINCT `mvu5877_anuncios_photos`.`image` ORDER BY `mvu5877_anuncios_photos`.`order` ASC SEPARATOR ',' LIMIT 4 ) AS `images

MySQL 5.7.32 中有更多语法错误。有什么建议吗?

标签: mysqllimitgroup-concat

解决方案


检查文档:GROUP_CONCAT()。在 GROUP_CONCAT() 调用中没有 LIMIT 关键字的语法。这是 MariaDB 特有的功能,在 MariaDB 10.3.3 中引入

在 MySQL 5.7 中,您必须使用子查询来限制结果,然后在外部查询中使用 GROUP_CONCAT():

mysql> select  group_concat( DISTINCT `image` ORDER BY `order` ASC SEPARATOR ',' ) AS `images` 
  from mytable;
+-----------------+
| images          |
+-----------------+
| abc,def,ghi,jkl |
+-----------------+

mysql> select group_concat( DISTINCT `image` ORDER BY `order` ASC SEPARATOR ',' ) AS `images` 
  from (select * from mytable limit 2) as t;
+---------+
| images  |
+---------+
| abc,def |
+---------+

推荐阅读