SQL语句中order by子句中使用的子查询的含义是什么?

huangapple go评论62阅读模式
英文:

What is the meaning of the subquery used in the order by clause of an SQL statement?

问题

The subquery used in the ORDER BY clause of an SQL statement retrieves the average (AVG) of the "amount" column from the "sales" table and orders the result set based on this average value.

英文:

What is the meaning of the subquery used in the order by clause of an SQL statement?

CREATE TABLE sales 
(
    id INT,
    name VARCHAR(50),
    amount INT
);

COMMIT;

INSERT INTO sales 
VALUES (1, 'John', 100),
       (2, 'Mary', 200),
       (3, 'Tom', 300),
       (4, 'Jane', 150),
       (5, 'Peter', 250);

SELECT AVG(amount) FROM sales;

SELECT * 
FROM sales
ORDER BY (SELECT AVG(amount) FROM sales);

SQL语句中order by子句中使用的子查询的含义是什么?

答案1

得分: 1

一个ORDER BY子查询是有道理的,但它必须是相关的,也就是说,子查询必须引用要排序的表的一行。如果我们想要首先列出平均销售额最低的人,我们可以这样写:

SELECT * 
FROM sales
ORDER BY (SELECT AVG(s.amount) FROM sales s WHERE s.name = sales.name),
         name,
         sales_date;

例如。

在你的示例中,子查询是相关的。销售的平均金额是一个数字。你告诉DBMS对行进行排序,但使用同一个数字作为每一行的排序键。不会发生排序。

英文:

A subquery in an ORDER BY clause can make sense, but it must be correlated then, i.e. the subquery would have to refer to a row of the table that is to be sorted. If we wanted to have the persons with the lowest average amount first, we could write:

SELECT * 
FROM sales
ORDER BY (SELECT AVG(s.amount) FROM sales s WHERE s.name = sales.name),
         name,
         sales_date;

for instance.

In your example, the subquery is not correlated. The average amount of sales is one number. You tell the DBMS to order the rows, but use that same number as a sortkey for every row. No sorting will take place.

huangapple
  • 本文由 发表于 2023年4月13日 19:51:12
  • 转载请务必保留本文链接:https://go.coder-hub.com/76005085.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定