Database subquery, database subquery

Source: Internet
Author: User

Database subquery, database subquery
Subquery

A select statement also contains another select statement, in which the select statement is called a subquery.

Subqueries can be divided into the following categories based on the position where select appears:

From subquery

Where subquery

Exists subquery

From the results returned by select, subqueries can be divided:

Scalar Query

The query result has only one value.

Example:

Requirement: query the classrooms where zhangsan is located

Ideas:

First, write and finally get the query = classroom

Select room from class ......

Query zhangsan by condition =

Where id = (select c_id from stu where s_name = 'hangsan ')

Column subquery

The query result is a column of data with multiple rows.

Requirements:

Query all students whose class is php

Select * from stu where c_id = (select id from class where c_name = 'php ');

Query all students whose classes are php and ios.

Select * from stu where c_id in (select id from class where c_name = 'php' or c_name = 'ios ');

Example:

Row subquery

The query result is one row and multiple columns.

Requirement: query the maximum number of records in the student table with sex 1 and age

Select * from stu where (age, sex) = (select max (age), sex from stu where sex = 1 );

Example:

Table subquery

The result is a table, which is equivalent to a data source.

Requirements:

Query the largest age of students in each class.

Example:

Exists subquery

Exists is equivalent to judgment

Requirements:

Query php students

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.