简体   繁体   English

无法排序查询,SQL数据库表

[英]Unable to sort and query, SQL database Table

I'm trying to understand the dynamics of mysql, And I'm not able to understand this error statement:我正在尝试了解 mysql 的动态,但我无法理解此错误语句:

Query:-询问:-

SELECT employee_id, First_name, Salary AS Pay FROM employee
ORDER BY Salary DESC
WHERE Salary > 70000
LIMIT 3;

I want to retrieve data from the employee table and then sort it up & only take out only the ones which are greater than 7000 .我想从employee表中检索数据,然后对其进行排序,并且只取出greater than 7000 But instead i Get this error,但是我得到了这个错误,

ER_PARSE_ERROR: You have an error in your SQL syntax; ER_PARSE_ERROR:您的 SQL 语法有错误; check the manual that corresponds to your MySQL server version for the right syntax to use near 'WHERE Salary > 70000 LIMIT 3' at line 1检查与您的 MySQL 服务器版本相对应的手册,了解在第 1 行的“WHERE Salary > 70000 LIMIT 3”附近使用的正确语法

But , If the code is written this way,但是,如果代码是这样写的,

SELECT employee_id, First_name, Salary AS Pay FROM employee
WHERE Salary > 70000
ORDER BY Salary DESC
LIMIT 3;

It runs, perfectly.它运行,完美。 But the query has a complete different meaning.但是查询具有完全不同的含义。

I hope you can understand what i mean, Why can't we query after sorting the table?我希望你能理解我的意思,为什么我们不能在对表进行排序后进行查询?

SQL is a descriptive language, not a procedural language. SQL 是一种描述性语言,而不是一种过程语言。

A SQL query describes the result set. SQL 查询描述了结果集。 Whether you remove rows with salary > 7000 and then sort, or sort and then remove them, you actually get the same answer.无论是删除salary > 7000然后排序,还是排序然后删除它们,您实际上都会得到相同的答案。

You don't get to specify the order of operations;您无需指定操作顺序; that is the job of the SQL compiler and optimizer.这就是 SQL 编译器和优化器的工作。

you can sort before you select by a trick of sub selecting ie:您可以在选择之前通过子选择技巧进行排序,即:

SELECT * FROM (SELECT employee_id, First_name, Salary AS Pay FROM employee
ORDER BY Salary DESC) a
WHERE Pay > 70000
LIMIT 3;

Mysql will first create a temporary memory table with ordered content and then your where will be applied to that table as will the limit. Mysql 将首先创建一个包含有序内容的临时内存表,然后你的 where 将和限制一样应用于该表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM