Home  >  Article  >  Database  >  MySQL code example to implement one-to-many query

MySQL code example to implement one-to-many query

不言
不言forward
2019-02-14 11:27:333779browse

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', '美术');

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;

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;

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!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete
Previous article:What is RedisNext article:What is Redis