MySQL Table Sub-query

Source: Internet
Author: User

MySQL Table Sub-query

A table subquery is a table data in which the result set returned by a subquery is n rows n columns.

MySQL Table Sub-query instance

Here are two original data tables for the example:

Article table:
Aid title content UID
1 Article 1 Article 1 body content ... 1
2 Article 2 Article 2 body content ... 1
3 Article 3 Article 3 body content ... 2
4 Article 4 Article 4 body content ... 3
Blog table:
Bid title content UID
1 Log 1 Log 1 body content ... 1
2 Article 2 Article 2 body content ... 1
3 Article 3 Article 3 body content ... 2

SQL is as follows:

SELECT * FROM article WHERE (title,content,uid) in (select Title,content,uid from blog)

The results of the query return are as follows:

Aid title content UID
2 Article 2 Article 2 body content ... 1
3 Article 3 Article 3 body content ... 2

Compared to the previous row subquery example, the row subquery in the WHERE bid=2 condition limit is removed, the data returned is a table record (of course, if the qualifying record only one, and become a row subquery records, but we think this is a table subquery).

The meaning of this SQL is to find all the rows in the article table that also exist in the blog table (Note = The comparison operator is replaced by in), which is actually equivalent to the following conditional statement:

SELECT * from Article,blog WHERE (Article.title=blog.title and Article.content=blog.content and Article.uid=blog.uid)

In fact, the subsequent statements are optimized for MySQL and more efficient, or can be implemented using a MySQL join table connection. This example is used only for the purposes of describing the use of table subqueries.

Derived data table sub-query

The table subquery applies more cases to the derived data table subquery, which is to execute the subquery first to generate the temporary table, and the outer main query to get the data in this temporary table. See MySQL from sub-query for details.

MySQL Table Sub-query

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.