Summary: in this tutorial, we will show you how to use the MySQL subquery to write complex queries and explain the correlated subquery concept.

A MySQL subquery is a query that is nested inside another query such as SELECTINSERTUPDATEor DELETE. In addition, a MySQL subquery can be nested inside another subquery.

A MySQL subquery is also called an inner query while the query that contains the subquery is called an outer query.

Let’s take a look at the following subquery that returns employees who locate in the offices in the USA.

  • The subquery returns all offices codes of the offices that locate in the USA.
  • The outer query selects the last name and first name of employees whose office code is in the result set returned by the subquery.

You can use a subquery anywhere that you use an expression. In addition, you must enclose a subquery in parentheses.

MySQL subquery within a WHERE clause

We will use the payments table for the demonstration.

MySQL subquery with comparison operators

You can use comparison operators e.g., =, >, <, etc., to compare a single value returned by the subquery with the expression in the WHERE clause.

For example, the following query returns the customer who has the maximum payment.

SELECT customerNumber,
checkNumber,
amount
FROM payments
WHERE amount = (
SELECT MAX(amount)
FROM payments
);

In addition to the equality operator, you can use other comparison operators such as greater than (>), less than(<), etc.

For example, you can find customers whose payments are greater than the average payment using a subquery.

First, you use a subquery to calculate the average payment using the AVG aggregate function. Then, in the outer query, you query payments that are greater than the average payment returned by the subquery.

SELECT customerNumber,
checkNumber,
amount
FROM payments
WHERE amount > (
SELECT AVG(amount)
FROM payments
);

MySQL subquery with IN and NOT IN operators

If a subquery returns more than one value, you can use other operators such as INor NOT INoperator in the WHERE clause.

See the following customers and orders tables.

For example, you can use a subquery with NOT IN operator to find customer who has not ordered any products as follows:

SELECT customername
FROM customers
WHERE customerNumber NOT IN(
SELECT DISTINCT customernumber
FROM orders
);

MySQL subquery with EXISTS and NOT EXISTS

When a subquery is used with EXISTS or NOT EXISTS operator, a subquery returns a Boolean value of TRUE or FALSE. The subquery acts as an existence check.

In the following example, we select a list of customers who have at least one order with total sales greater than 10K.

First, we build a query that checks if there is, at least, one order with total sales greater than 10K:

SELECT
priceEach * quantityOrdered
FROM
orderdetails
WHERE
priceEach * quantityOrdered > 10000
GROUP BY
orderNumber;

The query returns 6 rows so that when we use it as a subquery, it will return TRUE; therefore the whole query will return all customers:

SELECT
customerName
FROM
customers
WHERE
EXISTS (
SELECT
priceEach * quantityOrdered
FROM
orderdetails
WHERE
priceEach * quantityOrdered > 10000
GROUP BY
orderNumber
)

If you replace the EXISTS with NOT EXIST, the query will not return any records at all.

MySQL subquery in FROM clause

When you use a subquery in the FROM clause, the result set returned from a subquery is used as a table. This table is referred to as a derived table or materialized subquery.

The following subquery finds the maximumminimumand average number of items in sale orders:

SELECT
MAX(items),
MIN(items),
FLOOR(AVG(items))
FROM
(
SELECT
orderNumber,
COUNT(orderNumber) AS items
FROM
orderdetails
GROUP BY
orderNumber
) AS lineitems;

Notice that the subquery returns the following result set that is used as a derived table for the outer query.

MySQL correlated subquery

In the previous examples, you notice that the subquery is independent. It means you can execute the subquery as a single query. However, a correlated subquery is a subquery that uses the information from the outer query. In other words, a correlated subquery depends on the outer query. A correlated subquery is evaluated once for each row in the outer query.

In the following correlated subquery, we select products whose buy prices are greater than the average buy price of all products for a specific product line.

SELECT
productname,
buyprice
FROM
products AS p1
WHERE
buyprice > (
SELECT
AVG(buyprice)
FROM
products
WHERE
productline = p1.productline
)

The inner query executes for every product line because the product line is changed for every row. Hence, the average buy price will also change.

In this tutorial, we have shown you how to use MySQL subquery and correlated subquery to write more complex queries.

原文:http://www.mysqltutorial.org/mysql-subquery/

MySQL Subquery的更多相关文章

  1. MYSQL --Subquery returns more than 1 row查询结果多于一行

    Subquery returns more than 1 row表示子查询返回了多行数据 例如: select * from table1 where table1.colums=(select co ...

  2. MySQL----This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery

    This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'的意思是,这版本的 MySQL 不支持使 ...

  3. [慢查优化]慎用MySQL子查询,尤其是看到DEPENDENT SUBQUERY标记时

    案例梳理时间:2013-9-25 写在前面的话: 在慢查优化1和2里都反复强调过 explain 的重要性,但有时候肉眼看不出 explain 结果如何指导优化,这时候还需要有一些其他基础知识的佐助, ...

  4. This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery 解决方法

    This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'的意思是,这版本的 MySQL 不支持使 ...

  5. This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery' 解决办法

    背景:mysql5.1.36,mybatis 前言:为了解决一对多,分页显示,但是前端主要是显示的一的一方的数据和(多方的某个字段拼接在一起),此时的limit不能直接跟在查询的后面,需要用子查询把需 ...

  6. Mysql:1235 - This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'错误解决

    select distinct b.sale_count from product_sale b where b.pro_id in (select a.pro_id from product a L ...

  7. This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery

    This version of MySQL doesn't yet support 'LIMIT & IN/ALL/ANY/SOME subquery'的意思是,这版本的 MySQL 不支持使 ...

  8. MySQL Crash Course #07# Chapter 15. 关系数据库. INNER JOIN. VS. nested subquery

    索引 理解相关表. foreign key JOIN 与保持参照完整性 关于JOIN 的一些建议,子查询 VS. 联表查询 我发现MySQL 的官方文档里是有教程的. SQL Tutorial - W ...

  9. mysql 报错 ‘u'Subquery returns more than 1 row'’

    watch_course_sql ) , '%%Y-%%m-%%d %%T') regtime, a.username FROM bskuser a where a.UserName in (sele ...

随机推荐

  1. C# httpwebrequest post 传输百分号‘%’

    转载:http://blog.csdn.net/qqstrive/article/details/8229601 通过webrequest的post传输数据的时候,如果url里面的参数带有‘%’,那么 ...

  2. Javascript:父类可以调用子类吗?

    问:父类可以调用子类吗? 答:可以,经典的模板方法模式就是用的这个特性.

  3. TeX系列: MATLAB和LaTeX结合绘图

    目的是在MATLAB中绘图,在LaTeX中利用PGFPlots实现对图的修饰,比如坐标系.坐标轴标记.标题等等.这样能够保证图的中标记与正文文本的一致性,同时又可利用MATLAB强大的数据处理和丰富的 ...

  4. 使用maven的profile切换项目各环境的参数

    Java后端开发经常需要面对管理多套环境,一般有三种环境:开发,测试,生产. 各个环境之间的参数各不相同,比如MySQL.Redis等不同环境的host不一样,若每个环境都手动替换环境很容易出错,Ma ...

  5. 数字锁相环Octave仿真

    clc; clear all; % 仿真数据长度 SimLens = 1000; % 载波信号 Fs = 2400; Ts = 1 / Fs; Fsig = 60; % 随机初相 Delta_Phas ...

  6. DICOMDIR

    DICOMDIR 是一个可变长度 迷你 database 文件.由 group (0002, xxxx) 和 group (0004, xxxx) 为主题.描述的是一个 4 层的树状结构 (tree ...

  7. 如何更改postgresql的最大连接数

    改文件 postgresql.conf 里的 #max_connections=32 为 max_connections=1024 以及另外相应修改 share_buffer 参数.

  8. Windows10+Ubuntu双系统安装[

    数据备份先别着急,你备份了吗?如果你看到这里,说明你选择了风险最大的一条路,在游戏开始之前,一定要做好数据备份,数据备份,数据备份. 创建磁盘分区 按住Win + X,选择“磁盘管理”: 磁盘管理概览 ...

  9. ftm时钟源

    FTMx_SC中的 CLKS时钟选择位 00 :无 01: System clock 10:Fixed frequency clock 11 External clock 此处的01:System c ...

  10. 对SVM的个人理解---浅显易懂

    原文:http://blog.csdn.net/arthur503/article/details/19966891 之前以为SVM很强大很神秘,自己了解了之后发现原理并不难,不过,“大师的功力在于将 ...