MySQL table subquery's query

The concept of sub-queries

  1. The results of a query as a condition of another query

  2. There nested query, the query is called internal subquery

  3. Subquery to use parentheses

 

Subquery result of three cases

  1. The results of the sub-query is a single separate

  2. The results of the sub-query is a multi-line single row

  3. The results of the sub-query is a multiple columns and rows

 

The results of the sub-query is a value

SELECT query field FROM table WHERE field = (subquery);

Such as:

Students create a personal information form

CREATE TABLE students(
    Id INT(30),
    Name VARCHAR(10),
    Age INT(4),
    Gender VARCHAR(25),
    PRIMARY KEY(Id)
);

Create a table achievement

CREATE TABLE course(
    Id INT(30),
     Java INT(5),
     Python INT(5),
     MySQL INT(5),
     Hadoop INT(5),
     C INT(5),
     PHP INT(5),
     Linux INT(5),
     English INT(5),
     Math INT(5),
     CONSTRAINT id_course FOREIGN KEY(Id) REFERENCES students(Id)
);

Case: To inquire Java highest-achieving students information

SELECT * FROM students 
WHERE id =  (
    SELECT id FROM course 
    WHERE Java = (
        SELECT MAX(Java)FROM course
        )
    );

 

Subquery result is a multi-line single row

Subquery result is a single multi-line embodiment, an array similar to the result set, the parent query using the IN operator, or a BETWEEN ... AND ...

SELECT query field FROM table WHERE field in the IN (subquery);

Case: To inquire lower than the average of students' Java information

SELECT * FROM students
WHERE id BETWEEN
    (SELECT MIN(id) FROM course WHERE Java < (SELECT AVG(Java) FROM course))
    AND
    (SELECT MAX(id) FROM course WHERE Java < (SELECT AVG(Java) FROM course));

 

The results of the sub-query is a multiple columns and rows

Sub-query results as long as multiple columns, certainly in the back as a table FROM

SELECT query field the FROM (subquery) alias table WHERE condition;

Subquery table as required alias, otherwise this table has no name you can not access the fields in the table

Such as: student information query and Java, Python, English, Math achievement, and require larger than average Math score

The first step: query Java, Python, English, Math in all grades

SELECT Java, Python, English, Math, id FROM course AS course1

Step two: Query Math scores average

SELECT AVG(Math) FROM course

The third step: the use of table joins, student information queries, and requests for access to student subjects, and score requirements

SELECT * FROM students
INNER JOIN (SELECT Java, Python, English, Math, id FROM course) AS course1 ON students.Id = course1.Id
WHERE Math > (SELECT AVG(Math) FROM course);

 

Since the query Summary:

  • As long as a separate sub-query results, then later as a condition WHERE

  • Sub-query results as long as multiple columns, then the  secondary query as a table behind FROM 

     

Guess you like

Origin www.cnblogs.com/liyihua/p/12315552.html