回顾之前学习数据库的相关操作,复习时顺便记录下,以便以后自己可以再次查看!!!
/*
分组数据
*/
(1)select count(*) as num_prods
from products
where vend_id = 1003;//返回供应商1003提供的产品数目
(2)select vend_id, count(*) as num_prods
from products
group by vend_id;//返回了以vend_id列为单位,计算各类商品的总数
(3)select vend_id, count(*) as num_prods
from products
group by vend_id with rollup;// 使用WITH ROLLUP关键字,可以得到每个分组以 及每个分组汇总级别(针对每个分组)的值
(4)select cust_id, count(*) as orders
from orders
group by cust_id
having count(*) >= 2;//过滤了分组,只有总数大于等于2的分组才能留下了。
/*
注意:
WHERE过滤行,而HAVING过滤分组。
HAVING支持所有WHERE操作符 。
WHERE在数据 分组前进行过滤,HAVING在数据分组后进行过滤。
*/
(5)select vend_id, count(*) as num_prods
from products
where prod_price >= 10
group by vend_id
having count(*) >= 2;//列出具有2个(含)以上、价格 为10(含)以上的产品的供应商
(6)select vend_id, count(*) as num_prods
from products
group by vend_id
having count(*) >= 2;//返回了具有两个(含)以上的供应商,并且显示产品数目
/*
ORDER BY与GROUP BY :
ORDER BY GROUP BY
排序产生的输出 分组行。但输出可能不是分组的顺序
任意列都可以使用(甚至 非选择的列也可以使用) 只可能使用选择列或表达式列,而且必须使用每个选择列表达式
不一定需要 如果与聚集函数一起使用列(或表达式),则必须使用
*/
(7)select order_num, sum(quantity*item_price) as ordertotal
from orderitems
group by order_num
having sum(quantity*item_price) >= 50;//检索总计订单价格大于等于50的订 单的订单号和总计订单价格
(8)select order_num, sum(quantity*item_price) as ordertotal
from orderitems
group by order_num
having sum(quantity*item_price) >= 50
order by ordertotal;//检索总计订单价格大于等于50的订 单的订单号和总计订单价格,并且按照总计订单的价格排序输出。HAVING子 句过滤数据,使得只返回总计订单价格大于等于50的订单。后,用ORDER BY子句排序输出
/*
SELECT子句及其顺序 :
子 句 说 明 是否必须使用
SELECT 要返回的列或表达式 是
FROM 从中检索数据的表 仅在从表选择数据时使用
WHERE 行级过滤 否
GROUP BY 分组说明 仅在按组计算聚集时使用
HAVING 组级过滤 否
ORDER BY 输出排序顺序 否
LIMIT 要检索的行数 否
*/
/*
使用子查询
*/
(9)select order_num
from orderitems
where prod_id = 'TNT2';//返回了含有TNT2的所有订单物品,检索order_num列
(10)select cust_id
from orders
where order_num in (20005,20007);//查询含有订单20005和20007的客户ID
(11)select cust_id
from orders
where order_num in (select order_num
from orderitems
where prod_id = 'TNT2');//这就是一个子查询,先查询含有TNT2物品的所有订单号,然后再查询含有该订单号的所有客户ID
/*
注意:
子查询总是从内到外处理
*/
(12)select cust_name, cust_contact
from customers
where cust_id in(10001,10004);//返回了订购物品TNT2的所有客户的ID的客户信息
(13)select cust_name, cust_contact
from customers
where cust_id in(select cust_id
from orders
where order_num in (select order_num
from orderitems
where prod_id = 'TNT2'));//这也是一个子查询,返回了订购物品TNT2的所有客户的ID的客户信息
/*
注意:列必须匹配
在WHERE子句中使用子查询(如这里所示),应 该保证SELECT语句具有与WHERE子句中相同数目的列。
*/
(14)select count(*) as orders
from orders
where cust_id = 10001;//对客户10001的订单进行计数
(15)select cust_name,
cust_state,
(select count(*)
from orders
where orders.cust_id = customers.cust_id) as orders
from customers
order by cust_name;//这条SELECT 语句对customers 表中每个客户返回3列: cust_name、cust_state和orders。orders是一个计算字段, 它是由圆括号中的子查询建立的。该子查询对检索出的每个客户执行一 次。在此例子中,该子查询执行了5次,因为检索出了5个客户
数据库实际查询操作之相关数据库代码(MySQL必知必会数据库代码)