search
HomeDatabaseMysql TutorialMySQL code example to implement one-to-many query

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. If there is any infringement, please contact admin@php.cn delete
How to migrate from SQL Server to MySQLHow to migrate from SQL Server to MySQLAug 11, 2025 pm 04:09 PM

First, clear the answer: Migrating from SQLServer to MySQL requires evaluation, transformation, migration, testing and adjustment in steps. 1. Evaluate the source database, inventory the objects and identify dependency and incompatibility characteristics; 2. Map the data type differences, such as INTIDENTITY to INTAUTO_INCREMENT, NVARCHAR to VARCHAR and set the utf8mb4 character set, DATETIME maintains the corresponding, BIT to TINYINT(1), UNIQUEIDENTIFIER to CHAR(36) or BINARY(16); 3. Through the MySQLWorkbench migration wizard, manual export import or third-party tools such as AWSDMS

How to use the WHERE clause in MySQLHow to use the WHERE clause in MySQLAug 11, 2025 pm 03:54 PM

TheWHEREclauseinMySQLfiltersrecordsbasedonspecifiedconditions.1.ItisusedinSELECT,UPDATE,andDELETEstatementstoaffectonlymatchingrows.2.Comparisonoperatorslike=,!=,,=allowprecisefiltering.3.LogicaloperatorsAND,OR,andNOTcombinemultipleconditions,requiri

Implementing Row-Level Security in MySQLImplementing Row-Level Security in MySQLAug 11, 2025 pm 01:33 PM

MySQLdoesnothavebuilt-inrow-levelsecurity,butitcanbeimplementedusingviews,storedprocedures,andaccesscontrol.1.UseviewstofilterrowsbasedonthecurrentuserbyleveragingfunctionslikeCURRENT_USER()andamappingtabletorestrictdatavisibility.2.Restrictdirecttab

How to compare two tables for differences in MySQLHow to compare two tables for differences in MySQLAug 11, 2025 pm 12:14 PM

To compare the differences between two tables in MySQL, different operations need to be performed according to the structure, data or both: 1. When comparing the table structure, use DESCRIBE or query INFORMATION_SCHEMA.COLUMNS to find columns that exist only in one table through UNIONALL and subqueries; 2. When comparing table data, use LEFTJOIN combined with ISNULL conditions to find rows that exist only in table1 or table2, and use UNIONALL to merge the results with UNIONALL; 3. When comparing rows with the same primary key but different data, use JOIN to connect the two tables and use NULL safe comparison operator to detect the difference in the values of each column; 4. You can first perform row count statistics checks and compare them through COUNT(*)

Optimizing MySQL for High-Throughput Message QueuesOptimizing MySQL for High-Throughput Message QueuesAug 11, 2025 am 11:26 AM

TouseMySQLefficientlyasamessagequeueunderhigh-throughputworkloads,followthesesteps:1)UseInnoDBwithproperindexing—createcompositeindexesonselectivefieldslikequeue_nameandstatus,avoidexcessiveindexestomaintaininsertperformance.2)Usebatchoperations—inse

How to back up a database in MySQLHow to back up a database in MySQLAug 11, 2025 am 10:40 AM

Using mysqldump is the most common and effective way to back up MySQL databases. It can generate SQL scripts containing table structure and data. 1. The basic syntax is: mysqldump-u[user name]-p[database name]>backup_file.sql. After execution, enter the password to generate a backup file. 2. Back up multiple databases with --databases option: mysqldump-uroot-p--databasesdb1db2>multiple_dbs_backup.sql. 3. Back up all databases with --all-databases: mysqldump-uroot-p

How to use CASE statements in MySQLHow to use CASE statements in MySQLAug 11, 2025 am 10:29 AM

SearchedCASEisusedforcomplexconditionswithexplicitcomparisonslike>,

How to perform a case-insensitive search in MySQL?How to perform a case-insensitive search in MySQL?Aug 11, 2025 am 09:47 AM

MySQL is case-insensitive by default. Usually, _ci collation is used to achieve case-insensitive search; 1. Use the default case-insensitive collation (such as utf8mb4_general_ci) to make equal value comparisons and LIKE automatically ignore case; 2. Use LOWER() or UPPER() functions to convert the comparison to the same case to the same case, but be careful to affect the index usage; 3. Use COLLATE to specify temporary case-insensitive collation to overwrite the original settings of the column; 4. MySQL does not support the ILIKE operator, and LIKE combined with LOWER() or COLLATE to achieve similar functions; the best practice is to ensure that the column uses _ci collation

See all articles

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.