MySQL——sql语句的执行顺序

时间:2021-04-03 08:32:10

#核心知识点

书写顺序:where——》group by——》having——》order by——》limit

许多时候在书写一些复杂的sql语句的时候,尤其是在渐进式推导的时候,经常想要添加一些条件,但是却不知道往哪里加,也许进过许多次尝试之后成功了,但是下次又不知道了,因此总结就显得非常重要了。

首先给出sql语句的查询(或书写)顺序:

(7)    SELECT
(8) DISTINCT <select_list> #去重
(1) FROM <left_table>
(3) <join_type> JOIN <right_table> #左、右、内链接的一种
(2) ON <join_condition>
(4) WHERE <where_condition> #条件查询
(5) GROUP BY <group_by_list> #分组
(6) HAVING <having_condition> #分组后过滤
(9) ORDER BY <order_by_condition> #排序
(10) LIMIT <limit_number> #分页

上面从上到下是sql语句的书写顺序,前面括号代表它的执行顺序。

只有弄清楚书写顺序,我们写好的查询语句才不会出现语法错误,

只有弄清楚执行顺序,才能得到想要得到的结果。

关于书写我们要记住关键字:where——》group by——》having——》order by——》limit

下面给出一个例子,帮助理解:

有表table1和table2,需要查询来自杭州,且订单数小于2的客户。

表一:

mysql> select * from table1;
+-------------+----------+
| customer_id | city |
+-------------+----------+
| 163 | hangzhou |
| 9you | shanghai |
| baidu | hangzhou |
| tx | hangzhou |
+-------------+----------+
4 rows in set (0.00 sec)

表二:

mysql> select * from table2;
+----------+-------------+
| order_id | customer_id |
+----------+-------------+
| 1 | 163 |
| 2 | 163 |
| 3 | 9you |
| 4 | 9you |
| 5 | 9you |
| 6 | tx |
| 7 | NULL |
+----------+-------------+
7 rows in set (0.00 sec)

使用两种方法来解答:

第一种,使用子查询

#来自杭州
SELECT * FROM table1 WHERE city = 'hangzhou';
+-------------+----------+
| customer_id | city |
+-------------+----------+
| 163 | hangzhou |
| baidu | hangzhou |
| tx | hangzhou |
+-------------+----------+ #订单小于2
SELECT * FROM table2
GROUP BY customer_id HAVING COUNT(customer_id)< 2; +----------+-------------+
| order_id | customer_id |
+----------+-------------+
| 7 | NULL |
| 6 | tx |
+----------+-------------+
#再过滤掉其中不符合的就行 #联合在一起
SELECT * FROM table2
WHERE customer_id in (SELECT customer_id FROM table1 WHERE city = 'hangzhou')
GROUP BY customer_id HAVING COUNT(customer_id)< 2; #结果:
+----------+-------------+
| order_id | customer_id |
+----------+-------------+
| 6 | tx |
+----------+-------------+

这种方法逻辑性比较鲜明。

2.第二种,使用内链接查询

(1)内链接

mysql> SELECT order_id,a.customer_id city FROM table2 a INNER JOIN table1 b
-> on a.customer_id = b.customer_id;
+----------+------+
| order_id | city |
+----------+------+
| 1 | 163 |
| 2 | 163 |
| 3 | 9you |
| 4 | 9you |
| 5 | 9you |
| 6 | tx |
+----------+------+

(2)地点是杭州

mysql> SELECT order_id,a.customer_id city FROM table2 a INNER JOIN table1 b
-> on a.customer_id = b.customer_id
-> WHERE city = 'hangzhou';
+----------+------+
| order_id | city |
+----------+------+
| 1 | 163 |
| 2 | 163 |
| 6 | tx |
+----------+------+

(3)小于两件

mysql> SELECT order_id,a.customer_id city FROM table2 a INNER JOIN table1 b
-> on a.customer_id = b.customer_id
-> WHERE city = 'hangzhou'
-> GROUP BY a.customer_id
-> HAVING COUNT(1) < 2;
+----------+------+
| order_id | city |
+----------+------+
| 6 | tx |
+----------+------+

使用内链接查询的效率会比子查询来的高,但是对个人的要求比较高。