Mysql基础(十二):sql语句执行步骤详解准备工作

Posted qiu-hua

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mysql基础(十二):sql语句执行步骤详解准备工作相关的知识,希望对你有一定的参考价值。

准备工作

先来一段伪代码,首先你能看懂么?

SELECT DISTINCT <select_list>
    FROM <left_table>
    <join_type> JOIN <right_table>
    ON <join_condition>
    WHERE <where_condition>
    GROUP BY <group_by_list>
    HAVING <having_condition>
    ORDER BY <order_by_condition>
    LIMIT <limit_number>

继续做以下的前期准备工作:

新建一个测试数据库TestDB;

create database TestDB;

创建测试表table1和table2;

 CREATE TABLE table1
 (
     customer_id VARCHAR(10) NOT NULL,
     city VARCHAR(10) NOT NULL,
     PRIMARY KEY(customer_id)
 )ENGINE=INNODB DEFAULT CHARSET=UTF8;
 
 CREATE TABLE table2
 (
     order_id INT NOT NULL auto_increment,
     customer_id VARCHAR(10),
     PRIMARY KEY(order_id)
 )ENGINE=INNODB DEFAULT CHARSET=UTF8;

插入测试数据;

 INSERT INTO table1(customer_id,city) VALUES(163,hangzhou);
 INSERT INTO table1(customer_id,city) VALUES(9you,shanghai);
 INSERT INTO table1(customer_id,city) VALUES(tx,hangzhou);
 INSERT INTO table1(customer_id,city) VALUES(baidu,hangzhou);
 
 INSERT INTO table2(customer_id) VALUES(163);
 INSERT INTO table2(customer_id) VALUES(163);
 INSERT INTO table2(customer_id) VALUES(9you);
 INSERT INTO table2(customer_id) VALUES(9you);
 INSERT INTO table2(customer_id) VALUES(9you);
 INSERT INTO table2(customer_id) VALUES(tx);
 INSERT INTO table2(customer_id) VALUES(NULL);

准备工作做完以后,table1和table2看起来应该像下面这样:

     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)

准备SQL逻辑查询测试语句

     SELECT a.customer_id, COUNT(b.order_id) as total_orders
     FROM table1 AS a
     LEFT JOIN table2 AS b
     ON a.customer_id = b.customer_id
     WHERE a.city = hangzhou
     GROUP BY a.customer_id
     HAVING count(b.order_id) < 2
     ORDER BY total_orders DESC;

使用上述SQL查询语句来获得来自杭州,并且订单数少于2的客户。

 

以上是关于Mysql基础(十二):sql语句执行步骤详解准备工作的主要内容,如果未能解决你的问题,请参考以下文章

mysql基础篇 - SELECT 语句详解

MySQL阶段二——sql语句基础

Linux--MySQL 高级(进阶) SQL 语句

mysql怎么一次执行多条SQL语句

MySQL执行计划Explain参数详解

mysql执行计划详解各字段说明