文本处理函数
yyyy-mm-dd
",即2015-09-01Date
函数,只获取日期部分select cust_id, order_num
from order
where Date(order_date) = '2005-09-01';
聚集函数
聚集函数运行在行组上,计算和返回单个值
值或者日期
,忽略NULL聚集不同的值
默认
的DISRINCT
select AVG(DISTINCT prod_price) AS avg_price
from products
where vend_id = 1003;
创建分组
select vend_id,count(*) AS num_prods
from products
GROUP BY vend_id;
对每个组
,而不是整个结果集进行聚集过滤分组
where过滤的是行而不是分组
过滤的是分组
select vend_id,count(*) AS num_prods
from products
GROUP BY vend_id
HAVING count(*) > 2;
where和having的区别
- where是在分组前进行过滤
- having过滤的是分组后的数据
group by输出的不一定的分组的顺序
select order_num , sum(quantity*item_price) AS ordertotal
from orderitems
group by order_num
having sum(quantity*item_price) >=50
order by sum(quantity*item_price) ;
利用子查询进行过滤
select cust_id from orders where order_num in
(
select order_num from orderitems where prod_id = 'TNT2'
);
可以作为字段使用的子查询
SELECT cust_name,cust_state,
(SELECT COUNT(*)
FROM orders o
WHERE o.cust_id = c.cust_id
) AS orders
FROM customers c
ORDER BY cust_name;
创建联结
SELECT vend_name ,prod_name,prod_price
FROM vendors v ,products p
WHERE v.`vend_id` = p.`vend_id`
ORDER BY vend_name,prod_name;
避免二义性
笛卡尔积
内联结
基于两个表之间的相等
,也称作内连接SELECT vend_name ,prod_name,prod_price
FROM vendors v INNER JOIN products p
ON v.`vend_id` = p.`vend_id`
ORDER BY vend_name,prod_name;
这个结果与上述的一样
SQL规范应该使用ON
,使用where会影响性能
联结多个表
SELECT prod_name, vend_name, prod_name, quantity
FROM orderitems, products, vendors
WHERE products.`vend_id` = vendors.`vend_id`
AND orderitems.`prod_id` = products.`prod_id`
AND order_num = 20005;
自连接
在相同的表中处理数据
,可以使用自连接SELECT p1.prod_id, p1.prod_name
FROM products p1, products p2
WHERE p1.`vend_id` = p2.`vend_id` AND p2.`prod_id` = 'DTNTR';
*
可以返回全部的列外部联结
联结包含了在相关表中没有关联的行
,这种叫做外连接SELECT c.`cust_id`, o.`order_num`
FROM customers c INNER JOIN orders o
ON c.`cust_id` = o.`cust_id`;
SELECT c.`cust_id`, o.`order_num`
FROM customers c LEFT OUTER JOIN orders o
ON c.`cust_id` = o.`cust_id`;
检索所有的用户,包括哪些没有订单的用户
SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price<=5
UNION
SELECT vend_id, prod_id, prod_price
FROM products
WHERE vend_id IN (1001,1002);
SELECT vend_id, prod_id, prod_price
FROM products
WHERE prod_price<=5
UNION ALL
SELECT vend_id, prod_id, prod_price
FROM products
WHERE vend_id IN (1001,1002);