Home > Database > Mysql Tutorial > body text

MySQL code example to implement one-to-many query

不言
Release: 2019-02-14 11:27:33
forward
3568 people have browsed it

The content of this article is about the code example of MySQL implementing one-to-many query. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

What we want to implement this time is a one-to-many query, which is implemented using MySQL’s group_concat function.

group_concat

Simply put, the function of this function is to connect multiple fields. For a detailed explanation of the function, please see this article.

Data table

First we create two tables

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` char(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of student
-- ----------------------------
INSERT INTO `student` VALUES ('1', 'tom');
INSERT INTO `student` VALUES ('2', 'jerry');

CREATE TABLE `course` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `s_id` int(11) NOT NULL,
  `c_name` char(10) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of course
-- ----------------------------
INSERT INTO `course` VALUES ('1', '1', '语文');
INSERT INTO `course` VALUES ('2', '1', '数学');
INSERT INTO `course` VALUES ('3', '2', '英语');
INSERT INTO `course` VALUES ('4', '2', '体育');
INSERT INTO `course` VALUES ('5', '2', '美术');
Copy after login

Instance

If we use the usual SQL query

SELECT s.`name`,c.`c_name` FROM student AS s LEFT JOIN course AS c ON c.s_id = s.id;
Copy after login

The result of the query is

MySQL code example to implement one-to-many query

Use the group_concat function query

SELECT s.`name`,(SELECT group_concat(course.c_name) FROM course WHERE course.s_id = s.id) FROM student AS s;
Copy after login

to query at this time the result of

MySQL code example to implement one-to-many query

The above is the detailed content of MySQL code example to implement one-to-many query. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!