select cust_id, count(*) as num from orders groupby cust_id havingcount(*) >2; select vend_id, count(*) as num from products where price >10groupby vend_id, havingcount(*) >2orderby name;
子查询
1 2
# 显示costomer表中每个客户的订单数,订单和相应的客户ID存储在orders表中 select cust_name, cust_state, (selectcount(*) from orders where orders.cust_id = customers.cust_id) as num from customers orderby cust_name;
select vend_name, prod_name, prod_price from vendors, products orderby vend_name, prod_name;
等值联结
1
select vend_name, prod_name, prod_price from vendors innerjoin products on vendors.vend_id = products.vend_id;
外部联结
对每个客户下了多少订单进行计数,包括那些至今尚未下订单的客户
列出所有产品及订购数量,包括没有人订购的产品
1
select customer.cust_id, orders.order_num from customers leftouterjoin orders on customers.cust_id = orders.cust_id;
组合查询
union必须由两条或两条以上的select语句组成
union中的每个查询必须包含相同的列、表达式或聚集函数
列数据类型必须兼容:类型不必完全相同,但是可以隐含转换的类型
1 2 3
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);
union默认自动去除重复的行,如果需要返回所有匹配的行,可以使用union all
1 2 3
select vend_id, prod_id, prod_price from products where prod_price <5 unionall 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 select vend_id, prod_id, prod_price from products where vend_id in (1001, 1002) orderby vend_id, prod_price;