准备工作

mysql 语句

  1. ########################################
  2. # MySQL Crash Course
  3. # http://www.forta.com/books/0672327120/
  4. # Example table creation scripts
  5. ########################################
  6. ########################
  7. # Create customers table
  8. ########################
  9. CREATE TABLE customers
  10. (
  11. cust_id int NOT NULL AUTO_INCREMENT,
  12. cust_name char(50) NOT NULL ,
  13. cust_address char(50) NULL ,
  14. cust_city char(50) NULL ,
  15. cust_state char(5) NULL ,
  16. cust_zip char(10) NULL ,
  17. cust_country char(50) NULL ,
  18. cust_contact char(50) NULL ,
  19. cust_email char(255) NULL ,
  20. PRIMARY KEY (cust_id)
  21. ) ENGINE=InnoDB;
  22. #########################
  23. # Create orderitems table
  24. #########################
  25. CREATE TABLE orderitems
  26. (
  27. order_num int NOT NULL ,
  28. order_item int NOT NULL ,
  29. prod_id char(10) NOT NULL ,
  30. quantity int NOT NULL ,
  31. item_price decimal(8,2) NOT NULL ,
  32. PRIMARY KEY (order_num, order_item)
  33. ) ENGINE=InnoDB;
  34. #####################
  35. # Create orders table
  36. #####################
  37. CREATE TABLE orders
  38. (
  39. order_num int NOT NULL AUTO_INCREMENT,
  40. order_date datetime NOT NULL ,
  41. cust_id int NOT NULL ,
  42. PRIMARY KEY (order_num)
  43. ) ENGINE=InnoDB;
  44. #######################
  45. # Create products table
  46. #######################
  47. CREATE TABLE products
  48. (
  49. prod_id char(10) NOT NULL,
  50. vend_id int NOT NULL ,
  51. prod_name char(255) NOT NULL ,
  52. prod_price decimal(8,2) NOT NULL ,
  53. prod_desc text NULL ,
  54. PRIMARY KEY(prod_id)
  55. ) ENGINE=InnoDB;
  56. ######################
  57. # Create vendors table
  58. ######################
  59. CREATE TABLE vendors
  60. (
  61. vend_id int NOT NULL AUTO_INCREMENT,
  62. vend_name char(50) NOT NULL ,
  63. vend_address char(50) NULL ,
  64. vend_city char(50) NULL ,
  65. vend_state char(5) NULL ,
  66. vend_zip char(10) NULL ,
  67. vend_country char(50) NULL ,
  68. PRIMARY KEY (vend_id)
  69. ) ENGINE=InnoDB;
  70. ###########################
  71. # Create productnotes table
  72. ###########################
  73. CREATE TABLE productnotes
  74. (
  75. note_id int NOT NULL AUTO_INCREMENT,
  76. prod_id char(10) NOT NULL,
  77. note_date datetime NOT NULL,
  78. note_text text NULL ,
  79. PRIMARY KEY(note_id),
  80. FULLTEXT(note_text)
  81. ) ENGINE=MyISAM;
  82. #####################
  83. # Define foreign keys
  84. #####################
  85. ALTER TABLE orderitems ADD CONSTRAINT fk_orderitems_orders FOREIGN KEY (order_num) REFERENCES orders (order_num);
  86. ALTER TABLE orderitems ADD CONSTRAINT fk_orderitems_products FOREIGN KEY (prod_id) REFERENCES products (prod_id);
  87. ALTER TABLE orders ADD CONSTRAINT fk_orders_customers FOREIGN KEY (cust_id) REFERENCES customers (cust_id);
  88. ALTER TABLE products ADD CONSTRAINT fk_products_vendors FOREIGN KEY (vend_id) REFERENCES vendors (vend_id);
  1. ########################################
  2. # MySQL Crash Course
  3. # http://www.forta.com/books/0672327120/
  4. # Example table population scripts
  5. ########################################
  6. ##########################
  7. # Populate customers table
  8. ##########################
  9. INSERT INTO customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email)
  10. VALUES(10001, 'Coyote Inc.', '200 Maple Lane', 'Detroit', 'MI', '44444', 'USA', 'Y Lee', 'ylee@coyote.com');
  11. INSERT INTO customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact)
  12. VALUES(10002, 'Mouse House', '333 Fromage Lane', 'Columbus', 'OH', '43333', 'USA', 'Jerry Mouse');
  13. INSERT INTO customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email)
  14. VALUES(10003, 'Wascals', '1 Sunny Place', 'Muncie', 'IN', '42222', 'USA', 'Jim Jones', 'rabbit@wascally.com');
  15. INSERT INTO customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact, cust_email)
  16. VALUES(10004, 'Yosemite Place', '829 Riverside Drive', 'Phoenix', 'AZ', '88888', 'USA', 'Y Sam', 'sam@yosemite.com');
  17. INSERT INTO customers(cust_id, cust_name, cust_address, cust_city, cust_state, cust_zip, cust_country, cust_contact)
  18. VALUES(10005, 'E Fudd', '4545 53rd Street', 'Chicago', 'IL', '54545', 'USA', 'E Fudd');
  19. ########################
  20. # Populate vendors table
  21. ########################
  22. INSERT INTO vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)
  23. VALUES(1001,'Anvils R Us','123 Main Street','Southfield','MI','48075', 'USA');
  24. INSERT INTO vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)
  25. VALUES(1002,'LT Supplies','500 Park Street','Anytown','OH','44333', 'USA');
  26. INSERT INTO vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)
  27. VALUES(1003,'ACME','555 High Street','Los Angeles','CA','90046', 'USA');
  28. INSERT INTO vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)
  29. VALUES(1004,'Furball Inc.','1000 5th Avenue','New York','NY','11111', 'USA');
  30. INSERT INTO vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)
  31. VALUES(1005,'Jet Set','42 Galaxy Road','London', NULL,'N16 6PS', 'England');
  32. INSERT INTO vendors(vend_id, vend_name, vend_address, vend_city, vend_state, vend_zip, vend_country)
  33. VALUES(1006,'Jouets Et Ours','1 Rue Amusement','Paris', NULL,'45678', 'France');
  34. #########################
  35. # Populate products table
  36. #########################
  37. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  38. VALUES('ANV01', 1001, '.5 ton anvil', 5.99, '.5 ton anvil, black, complete with handy hook');
  39. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  40. VALUES('ANV02', 1001, '1 ton anvil', 9.99, '1 ton anvil, black, complete with handy hook and carrying case');
  41. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  42. VALUES('ANV03', 1001, '2 ton anvil', 14.99, '2 ton anvil, black, complete with handy hook and carrying case');
  43. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  44. VALUES('OL1', 1002, 'Oil can', 8.99, 'Oil can, red');
  45. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  46. VALUES('FU1', 1002, 'Fuses', 3.42, '1 dozen, extra long');
  47. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  48. VALUES('SLING', 1003, 'Sling', 4.49, 'Sling, one size fits all');
  49. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  50. VALUES('TNT1', 1003, 'TNT (1 stick)', 2.50, 'TNT, red, single stick');
  51. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  52. VALUES('TNT2', 1003, 'TNT (5 sticks)', 10, 'TNT, red, pack of 10 sticks');
  53. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  54. VALUES('FB', 1003, 'Bird seed', 10, 'Large bag (suitable for road runners)');
  55. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  56. VALUES('FC', 1003, 'Carrots', 2.50, 'Carrots (rabbit hunting season only)');
  57. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  58. VALUES('SAFE', 1003, 'Safe', 50, 'Safe with combination lock');
  59. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  60. VALUES('DTNTR', 1003, 'Detonator', 13, 'Detonator (plunger powered), fuses not included');
  61. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  62. VALUES('JP1000', 1005, 'JetPack 1000', 35, 'JetPack 1000, intended for single use');
  63. INSERT INTO products(prod_id, vend_id, prod_name, prod_price, prod_desc)
  64. VALUES('JP2000', 1005, 'JetPack 2000', 55, 'JetPack 2000, multi-use');
  65. #######################
  66. # Populate orders table
  67. #######################
  68. INSERT INTO orders(order_num, order_date, cust_id)
  69. VALUES(20005, '2005-09-01', 10001);
  70. INSERT INTO orders(order_num, order_date, cust_id)
  71. VALUES(20006, '2005-09-12', 10003);
  72. INSERT INTO orders(order_num, order_date, cust_id)
  73. VALUES(20007, '2005-09-30', 10004);
  74. INSERT INTO orders(order_num, order_date, cust_id)
  75. VALUES(20008, '2005-10-03', 10005);
  76. INSERT INTO orders(order_num, order_date, cust_id)
  77. VALUES(20009, '2005-10-08', 10001);
  78. ###########################
  79. # Populate orderitems table
  80. ###########################
  81. INSERT INTO orderitems(order_num, order_item, prod_id, quantity, item_price)
  82. VALUES(20005, 1, 'ANV01', 10, 5.99);
  83. INSERT INTO orderitems(order_num, order_item, prod_id, quantity, item_price)
  84. VALUES(20005, 2, 'ANV02', 3, 9.99);
  85. INSERT INTO orderitems(order_num, order_item, prod_id, quantity, item_price)
  86. VALUES(20005, 3, 'TNT2', 5, 10);
  87. INSERT INTO orderitems(order_num, order_item, prod_id, quantity, item_price)
  88. VALUES(20005, 4, 'FB', 1, 10);
  89. INSERT INTO orderitems(order_num, order_item, prod_id, quantity, item_price)
  90. VALUES(20006, 1, 'JP2000', 1, 55);
  91. INSERT INTO orderitems(order_num, order_item, prod_id, quantity, item_price)
  92. VALUES(20007, 1, 'TNT2', 100, 10);
  93. INSERT INTO orderitems(order_num, order_item, prod_id, quantity, item_price)
  94. VALUES(20008, 1, 'FC', 50, 2.50);
  95. INSERT INTO orderitems(order_num, order_item, prod_id, quantity, item_price)
  96. VALUES(20009, 1, 'FB', 1, 10);
  97. INSERT INTO orderitems(order_num, order_item, prod_id, quantity, item_price)
  98. VALUES(20009, 2, 'OL1', 1, 8.99);
  99. INSERT INTO orderitems(order_num, order_item, prod_id, quantity, item_price)
  100. VALUES(20009, 3, 'SLING', 1, 4.49);
  101. INSERT INTO orderitems(order_num, order_item, prod_id, quantity, item_price)
  102. VALUES(20009, 4, 'ANV03', 1, 14.99);
  103. #############################
  104. # Populate productnotes table
  105. #############################
  106. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  107. VALUES(101, 'TNT2', '2005-08-17',
  108. 'Customer complaint:
  109. Sticks not individually wrapped, too easy to mistakenly detonate all at once.
  110. Recommend individual wrapping.'
  111. );
  112. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  113. VALUES(102, 'OL1', '2005-08-18',
  114. 'Can shipped full, refills not available.
  115. Need to order new can if refill needed.'
  116. );
  117. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  118. VALUES(103, 'SAFE', '2005-08-18',
  119. 'Safe is combination locked, combination not provided with safe.
  120. This is rarely a problem as safes are typically blown up or dropped by customers.'
  121. );
  122. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  123. VALUES(104, 'FC', '2005-08-19',
  124. 'Quantity varies, sold by the sack load.
  125. All guaranteed to be bright and orange, and suitable for use as rabbit bait.'
  126. );
  127. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  128. VALUES(105, 'TNT2', '2005-08-20',
  129. 'Included fuses are short and have been known to detonate too quickly for some customers.
  130. Longer fuses are available (item FU1) and should be recommended.'
  131. );
  132. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  133. VALUES(106, 'TNT2', '2005-08-22',
  134. 'Matches not included, recommend purchase of matches or detonator (item DTNTR).'
  135. );
  136. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  137. VALUES(107, 'SAFE', '2005-08-23',
  138. 'Please note that no returns will be accepted if safe opened using explosives.'
  139. );
  140. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  141. VALUES(108, 'ANV01', '2005-08-25',
  142. 'Multiple customer returns, anvils failing to drop fast enough or falling backwards on purchaser. Recommend that customer considers using heavier anvils.'
  143. );
  144. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  145. VALUES(109, 'ANV03', '2005-09-01',
  146. 'Item is extremely heavy. Designed for dropping, not recommended for use with slings, ropes, pulleys, or tightropes.'
  147. );
  148. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  149. VALUES(110, 'FC', '2005-09-01',
  150. 'Customer complaint: rabbit has been able to detect trap, food apparently less effective now.'
  151. );
  152. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  153. VALUES(111, 'SLING', '2005-09-02',
  154. 'Shipped unassembled, requires common tools (including oversized hammer).'
  155. );
  156. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  157. VALUES(112, 'SAFE', '2005-09-02',
  158. 'Customer complaint:
  159. Circular hole in safe floor can apparently be easily cut with handsaw.'
  160. );
  161. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  162. VALUES(113, 'ANV01', '2005-09-05',
  163. 'Customer complaint:
  164. Not heavy enough to generate flying stars around head of victim. If being purchased for dropping, recommend ANV02 or ANV03 instead.'
  165. );
  166. INSERT INTO productnotes(note_id, prod_id, note_date, note_text)
  167. VALUES(114, 'SAFE', '2005-09-07',
  168. 'Call from individual trapped in safe plummeting to the ground, suggests an escape hatch be added.
  169. Comment forwarded to vendor.'
  170. );

SQL

SQL(发音为字母S-Q-L或sequel)是结构化查询语言(Structured Query Language)的缩写。SQL是一种专门用来与数据库通信的语言。

MySql

MySQL是一个客户机-服务器DBMS,因此,为了使用MySQL,需要有一个客户机,即你需要用来与MySQL打交道(给MySQL提供要执行的命令)的一个应用。

使用MySql

连接

连接MySql需要以下4个条件

  • 主机名(计算机名)——如果连接到本地MySQL服务器,为localhost;
  • 端口(如果使用默认端口3306之外的端口);
  • 一个合法的用户名;
  • 口用户口令(如果需要)。

命令行: mysql [-h主机号 -P端口号] -u用户名 -p密码

选择数据库

例如,为了使用crashcourse数据库,应该输入以下内容:
输入

  1. USE crashcourse;

输出

  1. Database changed

查看数据库和表

  1. show databases;//查看数据库
  2. show tables;//查看表
  3. show columns from tableName;//显示表结构
  4. describe tableName;//显示表结构(为上句的快捷方式)
  5. show create database tmp;//显示建数据库tmp的sql语句
  6. show create table person;//显示建表person的sql语句
  7. show stasus;//显示广泛的服务器状态信息
  8. show grants;//用来显示授予用户(所有用户或特定用户)的安全权限;
  9. SHOW ERRORSSHOW WARNINGS,用来显示服务器错误或警告消息。

MySql常用的SHOW语句:https://www.cnblogs.com/zhaoshujie/p/10422396.html

查找数据(select基本用法)

为了使用SELECT检索表数据,必须至少给出两条信息——想选择什么,以及从什么地方选择。

查找单列

  1. SELECT prod_name
  2. FROM products;

查找多列

  1. SELECT prod_id,prod_name,prod_price
  2. FROM products;

查找所有列

  1. SELECT *
  2. FROM products;

使用通配符
一般,除非你确实需要表中的每个列,否则最好别使用*通配符。
虽然使用通配符可能会使你自己省事,不用明确列出所需列,但检索不需要的列通常会降低检索和应用程序的性能。

检索不同行(distinct)

  1. select vend_id
  2. from products;//未去重
  3. select distinct vend_id
  4. from products;//去重

不能部分使用DISTINCT
DISTINCT关键字应用于所有列而不仅是前置它的列。
如果给出SELECT DISTINCT vend_ id,prod_price,除非指定的两个列都不同,否则所有行都将被检索出来。

  1. # 错误sql语句
  2. select vend_id, distinct prod_price
  3. from products;
  4. # 正确sql语句
  5. select distinct vend_id, prod_price
  6. from products;

限制结果

SELECT语句返回所有匹配的行,它们可能是指定表中的每个行。为了返回第一行或前几行,可使用LIMIT子句。

  1. select prod_name
  2. from products
  3. limit 5;

返回特定位置的结果,可以使用offset子句,跳过多少条语句。

  1. select prod_name
  2. from products
  3. limit 5 offset 5;

排序检索数据(order by子句)

关系数据库设计理论认为,如果不明确规定排序顺序,则不应该假定检索出的数据的顺序有意义。
子句(clause)
SQL语句由子句构成,有些子句是必需的,而有的是可选的。
一个子句通常由一个关键字和所提供的数据组成。
子句的例子有SELECT语句的FROM子句。

单列排序

  1. select prod_name
  2. from products
  3. order by prod_name;

多列排序

下面的代码检索3个列,并按其中两个列对结果进行排序—首先按价格,然后再按名称排序。

  1. select prod_id,prod_price,prod_name
  2. from products
  3. order by prod_price,prod_name;

排序方向(升序,降序)

下面的例子按价格以降序排序产品(最贵的排在最前面)

  1. select prod_id,prod_price,prod_name
  2. from products
  3. order by prod_price desc;

DESC关键字只应用到直接位于其前面的列名。只对prod_price列指定DESc,对prod_name列不指定。
因此,prod_price列以降序排序,而prod_name列(在每个价格内)仍然按标准的升序排序。

  1. select prod_id,prod_price,prod_name
  2. from products
  3. order by prod_price desc ,prod_name asc;

过滤数据(where子句)

数据库表一般包含大量的数据,很少需要检索表中所有行。
通常只会根据特定操作或报告的需要提取表数据的子集。
只检索所需数据需要指定搜索条件( search criteria ),搜索条件也称为过滤条件( filtercondition )。

Where子句操作符

image.png
WHERE子句的位置
在同时使用ORDER BY和WHERE子句时,应该让ORDER BY位于WHERE之后,否则将会产生错误。

  1. # 等于过滤
  2. select prod_name,prod_price
  3. from products
  4. where prod_name='fuses';
  5. # 不等于过滤
  6. select prod_name,prod_price
  7. from products
  8. where prod_name<>'fuses';
  9. # 范围过滤
  10. select prod_name,prod_price
  11. from products
  12. where prod_price between 5 and 10;
  13. # NULL值过滤
  14. select cust_id
  15. from customers
  16. where cust_email is null ;
  17. # 非NULL值过滤
  18. select cust_id
  19. from customers
  20. where cust_email is not null ;

Where子句组合

  • and

此SQL语句检索由供应商1003制造且价格小于等于10美元的所有产品的名称和价格。
这条SELECT语句中的WHERE子句包含两个条件,并且用AND关键字联结它们。

  1. select prod_id,prod_price,prod_name
  2. from products
  3. where vend_id=1003 and prod_price<=10;
  • or

    1. select prod_name,prod_price
    2. from products
    3. where vend_id=1002 or vend_id=1003;

    此SQL语句检索由任一个指定供应商制造的所有产品的产品名和价格。
    OR操作符告诉DBMS匹配任一条件而不是同时匹配两个条件。

  • and or组合

AND在计算次序中优先级更高

  1. # 默认先and 后 or
  2. select prod_name,prod_price
  3. from products
  4. where vend_id=1002 or vend_id =1003 and prod_price>=10;
  5. # 可以使用括号改变计算顺序
  6. select prod_name,prod_price
  7. from products
  8. where (vend_id=1002 or vend_id =1003) and prod_price>=10;

in操作符

in操作符用于指定条件的范围。

  1. select prod_name,prod_price
  2. from products
  3. where (vend_id=1002 or vend_id =1003) and prod_price>=10;

通配符

使用like操作符

%

匹配任意字符任意次
最常使用的通配符是百分号(%)。在搜索串中,%表示任何字符出现任意次数。
例如,为了找出所有以词jet起头的产品,可使用以下SELECT

  1. select prod_id,prod_name
  2. from products
  3. where prod_name like 'jet%';

_

匹配任意字符一次

  1. select prod_id,prod_name
  2. from products
  3. where prod_name like '_ ton anvil';

正则表达式

  1. # 匹配产品名称中有1000的数据
  2. select prod_name
  3. from products
  4. where prod_name regexp '1000'
  5. order by prod_name;
  6. # .代表匹配任意字符一次
  7. select prod_name
  8. from products
  9. where prod_name regexp '.000'
  10. order by prod_name;
  11. # |代表或者,匹配1000或者2000
  12. select prod_name
  13. from products
  14. where prod_name regexp '1000|2000'
  15. order by prod_name;
  16. # |代表或者,匹配1000或者2000
  17. select prod_name
  18. from products
  19. where prod_name regexp '1000|2000'
  20. order by prod_name;
  21. # []代表选择其中一个进行匹配
  22. select prod_name
  23. from products
  24. where prod_name regexp '[123] ton'
  25. order by prod_name;
  26. #[1-5]表示匹配 1-5
  27. select prod_name
  28. from products
  29. where prod_name regexp '[1-5] ton'
  30. order by prod_name;

转义字符:
为了匹配特殊字符,必须用\l为前导。\-表示查找-,\.表示查找.

计算字段

对数据库的数据进行简单计算得到的数据。

拼接(concat函数)

  1. select concat(vend_name,'(',vend_country,')') as msg
  2. from vendors
  3. order by vend_name;

修剪函数

  • Trim 去掉两边空格
  • LTrim 去掉左边空格
  • RTrim 去掉右边空格

别名:as 语句

  1. select concat(vend_name,'(',vend_country,')') as vend_title
  2. from vendors
  3. order by vend_name;

算数运算

  1. select prod_id,quantity,item_price,quantity*item_price as expanded_price
  2. from orderitems
  3. where order_num=20005;

函数

文本处理函数

  • Upper函数(转大写)

    1. select vend_name ,Upper(vend_name) as vend_name_upcase
    2. from vendors
    3. order by vend_name;
  • lower函数(转小写)

    1. select vend_name ,lower(vend_name) as vend_name_upcase
    2. from vendors
    3. order by vend_name;
  • Left函数(返回左边字符)

    1. # LEFT(str,length);
    2. select left('abcd',2);
  • length函数(返回字符串长度)

    1. select length('abcd');
  • locate函数(匹配子串)

    1. # locate(subStr,string)
    2. select locate('cd','abcd')

    image.png
    image.png

    日期和时间处理函数

    数据结构和类型

  • 日期格式

    • Date 存储数据格式为:YYYY-MM-DD,它支持的范围为’1000-01-01’到’9999-12-31’
    • DateTime 日期和时间的组合,存储格式为:YYYY-MM-DD HH:MM:SS,它支持的范围为’1000-01-01 00:00:00’到’9999-12-31 23:59:59’
    • Timestamp 时间戳,从1970-01-01 00:00:00到当前的时间差值
  • 时间类型
    • Time

MySQL中日期和时间类型
image.png

  1. # 日期比较 该语句无法匹配dataTime类型的 2005-09-01 12:00
  2. select cust_id,order_num
  3. from orders
  4. where order_date='2005-09-01';
  5. # 日期比较 该语句可以匹配dataTime类型的 2005-09-01 12:00
  6. select cust_id,order_num
  7. from orders
  8. where date(order_date)='2005-09-01';
  1. # 匹配特定月份的数据
  2. # 方案1 使用between操作符
  3. select cust_id,order_num
  4. from orders
  5. where date(order_date) between '2005-09-01' and '2005-09-30';
  6. # 方案2 使用year和month函数
  7. select cust_id,order_num
  8. from orders
  9. where year(order_date)=2005 and month(order_date)=9;

数值处理函数

image.png

数据汇总

聚集函数

  • Avg函数(平均值)

    1. use tmp;
    2. select avg(prod_price) as avg_price
    3. from products;
  • count函数(计数) ```sql SELECT COUNT(*) AS num_cust FROM customers;

count 函数不会统计NULL值

SELECT COUNT(cust_email) AS num_cust from customers;

  1. - **MAX函数(最大值)**
  2. ```sql
  3. select max(prod_price) as max_prod_price
  4. from products;
  • Min函数(最小值)

    1. select min(prod_price) as min_prod_price
    2. from products;
  • sum函数(求和)

    1. select sum(quantity) as sum_quantity
    2. from orderitems
    3. where order_num=20005;
  • 不同的值(distinct)

    1. # 统计不同产品价格的平均值
    2. SELECT AVG(DISTINCT prod_price) AS avg_price
    3. FROM products
    4. WHERE vend_id = 1003;

    数据分组

    分组语句

  • Group语句

    1. # 查询不同供应商的产品总数
    2. select vend_id,count(*) as num_prods
    3. from products
    4. group by vend_id;
  • having(过滤分组)

    1. select cust_id,count(*) as orders
    2. from orders
    3. group by cust_id
    4. having count(*)>=2;

HAVING和WHERE的差别
这里有另一种理解方法,WHERE在数据分组前进行过滤,HAVING在数据分组后进行过滤。这是一个重要的区别,WHERE排除的行不包括在分组中。这可能会改变计算值,从而影响HAVING子句中基于这些值过滤掉的分组。

  1. # 具有2个(含)以上、价格为10(含)以上的产品的供应商
  2. select vend_id,count(*) as num_prods
  3. from products
  4. where prod_price >=10
  5. group by vend_id
  6. having count(*)>=2;
  1. select order_num,sum(item_price*quantity) as total_price
  2. from orderItems
  3. group by order_num
  4. having sum(item_price*quantity)>50
  5. order by total_price;

select子句顺序

image.png

子查询

如何列出订购物品TNT2的所有客户?(orders,orderItems表)

  1. select *
  2. from customers
  3. where cust_id in(
  4. select cust_id
  5. from orders
  6. where order_num in(
  7. select order_num
  8. from orderItems
  9. where prod_id='tnt2'));
  10. select cust_id
  11. from orders left join orderItems on orders.order_num=orderItems.order_num
  12. where orderItems.prod_id='tnt2';

要显示customers表中每个客户的订单总数(order,customers表)

  1. select cust_name,cust_state,
  2. (select count(*)
  3. from orders
  4. where orders.cust_id=customers.cust_id) as orders
  5. from customers
  6. order by cust_name;
  7. select cust_name,cust_state,count(orders.order_num)
  8. from customers left join orders on customers.cust_id=orders.cust_id
  9. group by cust_name
  10. order by cust_name;

联结表