简体   繁体   中英

Using Limit with group_contact in MySQL 5

Good morning guys, I have a question:

I have the following sample SQL:

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

In SEPARATOR I need to define a quantity instead of bringing all the items. In MariaDB I can do this just past the Limit at the end. Example:

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

More in MySQL 5.7.32 the syntax error. Any suggestion?

Check the documentation: 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 .

In MySQL 5.7, you would have to use a subquery to limit the results, then use GROUP_CONCAT() in the outer query:

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 |
+---------+

You can use SUBSTRING_INDEX() so that you get the top 4 values in the results:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM