Mysql笔记(三)

  1. GROUP BY 分组允许把数据分为多个分组,以便能够对每个分组进行聚集计算。(获取每个供应商所提供的商品数量)

SELECT vend_id , count(*) as vend_num FROM products GROUP BY vend_id

  1. HAVING 过滤分组,(获取订单表中,订单次数大于等于2次的)

SELECT cust_id,count(*) AS count_num FROM orders GROUP BY cust_id HAVING count_num>=2

  1. 子查询 Mysql在4.1中引入了对子查询的支持,所以需要进行子查询的话,Mysql版本必须高于4.1。(获取订单表中购买物品是TNT2的客户信息)

SELECT cust_id FROM orders WHERE order_num IN (SELECT order_num FROM orderitems WHERE prod_id ='TNT2')

  1. 相关子查询 (获取每个客户的下单次数和客户信息)

SELECT cust_name,cust_address,(SELECT COUNT(*) FROM orders WHERE orders.cust_id=customers.cust_id )AS user_orders FROM customers

  1. 联表查询(在一条SELECT语句中联结几个表时,相应的关系是在运行时构造的。在数据库的定义中不存在能指示MYSQL对表进行联结的东西。在联结两个表的时候,你实际上做的是,将第一个表中的每一行数据和第二个表中的每一行数据进行匹配,WHERE子句作为过滤的条件。倘若没有联结条件的话,就是返回笛卡尔积 (第一个行数*第二表的行数))。

SELECT * FROM products,vendors WHERE products.vend_id=vendors.vend_id
SELECT * FROM products INNER JOIN vendors ON products.vend_id=vendors.vend_id

  1. 自联结 (自联结通常作为外部语句来替代相同表中检索数据时使用的子查询。有的时候处理联结远比子查询的速度快,所以需要多尝试一下,确定哪种的性能更好点)

SELECT COUNT(*) FROM products WHERE vend_id = (SELECT vend_id FROM products WHERE prod_id='DTNTR')
SELECT p1.prod_id,p1.prod_price FROM products as p1,products as p2 WHERE p1.vend_id=p2.vend_id AND p2.prod_id='DTNTR'

  1. 外部联结 (在使用 OUTER JOIN 语法的时候,必须使用LEFT 或者RIGHT关键字来指定所有的行。RIGHT是指OUTER JOIN右边的表)

SELECT orders.cust_id,orders.order_num AS 订单总数 FROM orders,customers WHERE orders.cust_id=customers.cust_id GROUP BY orders.cust_id
SELECT customers.cust_id,orders.order_num FROM customers LEFT OUTER JOIN orders ON customers.cust_id=orders.cust_id
SELECT customers.cust_id,orders.order_num FROM orders RIGHT OUTER JOIN customers ON customers.cust_id=orders.cust_id

  1. 组合查询 (UNION必须有两条或者两条以上的SELECT语句组合成的。UNION在查询结果集中会自动去除重复行,假设不想去除重复行的话可以使用UNION ALL)

SELECT prod_id, prod_name, prod_price FROM products WHERE vend_id in (1001,1002) #5
SELECT prod_id, prod_name, prod_price FROM products WHERE prod_price<=5 #4
SELECT prod_id, prod_name, prod_price FROM products WHERE vend_id in (1001,1002) UNION SELECT prod_id, prod_name, prod_price FROM products WHERE prod_price<=5

注意HAVING和WHERE之间的区别:

WHERE在数据分组前进行过滤,HAVING在数据分组后进行过滤。WHERE排除的行不包括在分组中,这可能会影响结果值。(综合WHERE和HAVING的查询,产品表中,价格大于等于10且产品数量大于2)

SELECT vend_id, COUNT(*) AS num FROM products WHERE prod_price>=10 GROUP BY vend_id HAVING num >=2

你可能感兴趣的:(Mysql笔记(三))