MySQL 一对多查询

栏目: 数据库 · 发布时间: 7年前

内容简介:这次要实现的是一对多查询,使用 MySQL 的简单来说,这个函数的作用就是连接多个字段,函数的具体详解可以看这篇首先我们先建立两个表

导语

这次要实现的是一对多查询,使用 MySQLgroup_concat 函数实现。

group_concat

简单来说,这个函数的作用就是连接多个字段,函数的具体详解可以看这篇 文章

数据表

首先我们先建立两个表

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

实例

如果我们用平时使用的 SQL 查询

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

查询出的结果是

MySQL 一对多查询

下面用 group_concat 函数查询

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

此时查询的结果

MySQL 一对多查询

参考资料: MySQL 的 GROUP_CONCAT 函数详解MySQL 一对多查询


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Writing Apache Modules with Perl and C

Writing Apache Modules with Perl and C

Lincoln Stein、Doug MacEachern / O'Reilly Media, Inc. / 1999-03 / USD 39.95

Apache is the most popular Web server on the Internet because it is free, reliable, and extensible. The availability of the source code and the modular design of Apache makes it possible to extend Web......一起来看看 《Writing Apache Modules with Perl and C》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

SHA 加密
SHA 加密

SHA 加密工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具