Home > Database > Mysql Tutorial > How Can I Limit the Number of Skills Shown in a GROUP_CONCAT Query to the Top Three?

How Can I Limit the Number of Skills Shown in a GROUP_CONCAT Query to the Top Three?

DDD
Release: 2024-11-26 14:38:10
Original
463 people have browsed it

How Can I Limit the Number of Skills Shown in a GROUP_CONCAT Query to the Top Three?

GROUP_CONCAT with Skill Limit

In a database with players and their skills in a many-to-many relationship, a query is needed to list players and their top three skills. The initial query attempts to use GROUP_CONCAT to concatenate skill titles, but it lacks a way to limit the number of skills to three.

Solution:

While GROUP_CONCAT does not directly support a limit, a workaround can be used by post-processing the concatenated string:

substring_index(group_concat(s.title SEPARATOR ','), ',', 3) as skills
Copy after login

This command extracts the first three skill titles separated by commas from the concatenated string. It assumes that skill names do not contain commas and that the number of skills is reasonably small.

Note:

To ensure correct results, the player_skills table should have a primary key consisting of the tuple (player_id, skill_id), preventing the same skill from being assigned to a player multiple times.

The above is the detailed content of How Can I Limit the Number of Skills Shown in a GROUP_CONCAT Query to the Top Three?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template