Get the App
SLTechnology News&Howtos  ›  Database  › 

How to write grouped fields into one line by mysql group_concat

Shulou Source: shulou.com Published: 2022-05-31 22:20:09 10月05日 Update

This article is about how mysql group_concat can write grouped fields on a single line. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.

Function: concatenate the values in the same group generated by group by and return a string result.

Function syntax:

Group_concat ([DISTINCT] the field to be connected [Order BY sort field ASC/DESC] [Separator 'delimiter'])

Example

Query the list of articles, using multiple tags for the same article as a field

Label table structure

CREATE TABLE `book_ tag` (`id` int (10) NOT NULL AUTO_INCREMENT, `tag_ name` varchar 'NOT NULL DEFAULT' 0' COMMENT 'tag name', `tag_ nums` int (10) NOT NULL DEFAULT'0' COMMENT 'reference', PRIMARY KEY (`id`) ENGINE=InnoDB DEFAULT CHARSET=utf8

Tagged article relation table

CREATE TABLE `tag_ book` (`id` int (10) NOT NULL AUTO_INCREMENT, `book_ id` int (10) NOT NULL DEFAULT'0' COMMENT 'book id', `tag_ id` int (10) NOT NULL DEFAULT' 0' COMMENT 'label ID', PRIMARY KEY (`id`) ENGINE=InnoDB DEFAULT CHARSET=utf8

Query

SELECT `b`.`book _ name`, `b`.`book _ flash`, `b`.`introduction`, GROUP_CONCAT (a.tag_name) FROM `book_ book``b`LEFT JOIN `book_tag_ book``t`t`.`book _ id` = `b`.`id`LEFT JOIN `book_ `taga`ON `a`.`id` = `t`.tag _ id`GROUP BY b.id

Result

Thank you for reading! This is the end of the article on "how to write grouped fields into one line in mysql group_concat". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, you can share it for more people to see!

Tags: Fields labels articles grouping one line content more articles results queries good practical books functions delimiters functions names multiple characters strings Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno OPPO Reno Shulou Tech Info vpn Shulou Information MariaDB