1. Basic knowledge of mysql subquery
A subquery is to embed a new query in the original query statement to get the result set we want.
Subqueries are generally divided into: where type subquery, from type subquery and exists type subquery.
1.where
type subquery: Use the inner query result as the comparison condition of the outer query.
select 列1,列2,...,列n from 表名 where 列i =/in (select 列1,列2,...,列n from 表名 where ...);
2.from
type subquery: treat the inner query results as a temporary table for the outer sql to query again. The query result set can be treated as a table. Temporary tables need to use an alias.
select 列1,列2,...,列n from (select 列1,列2,...,列n from 表名 where ...) as 表别名 where ....;
3.exists
Type subquery: Get the result of the outer sql to the inner sql for testing. If the inner sql is established, the row will be taken out. The inner query is the query after exists.
select 列1,列2,...,列n from 表名 where exists (select 列1,列2,...,列n from 表名 where ...);
2. Query Example
The following figure shows the grade table and class table data.
1. Query the information of the student with the highest math score in the score table;
2. Query each student in the score table The highest total grade of the class;
3. According to the grade table and class table, find the class with missing grades in the grade table;
Recommended tutorial: "sql tutorial"
The above is the detailed content of Subqueries are generally divided into several types. For more information, please follow other related articles on the PHP Chinese website!