在 MySQL 5 中对 group_contact 使用 Limit

Using Limit with group_contact in MySQL 5

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

我有以下示例 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语法错误。有什么建议吗?

查看文档:GROUP_CONCAT(). There is no syntax for a LIMIT keyword inside a GROUP_CONCAT() call. This is a feature specific to MariaDB, introduced in 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 |
+---------+

您可以使用 SUBSTRING_INDEX() 以便获得结果中的前 4 个值:

SUBSTRING_INDEX(
  GROUP_CONCAT(DISTINCT `mvu5877_anuncios_photos`.`image` ORDER BY `mvu5877_anuncios_photos`.`order`),
  ',',
  4
)