[MYSQL -16]创建高级联结
2017-09-18 09:55
295 查看
1、使用表别名
缩短SQL语句;允许在单条SELECT语句中多次使用相同的表
表别名只在查询执行使用中使用。与列别名不一样,表别名不返回到客户机。
select cust_name,cust_contact from customers as c,orders as o,orderitems as oi where c.cust_id = o.cust_id and oi.order_num= o.order_num and prod_id='TNT2';
2、自联结
单条SELECT语句中不止一次引用相同的表。子查询
select prod_id,prod_name from products where vend_id=(select vend_id from products where prod_id='DTNTR');
自联结
select prod_id,prod_name from products as p1,products as p2 where p1.vend_id=products.vend_id and products.prod_id='DTNTR';
自联结通常作为外部语句用来替代从相同表中检索数据时使用的子查询语句。虽然与子查询结果是相同的,但有时候比子查询快的多。
3、自然联结
只能选择那些唯一的列,通过对表使用通配符(SELECT *),对所有其他表的列使用明确地子集来完成。自然联结排除多次出现,每个列只返回一次。select c.*,o.order_num,o.order_date,oi.prod_id,oi.quantity,oi.item_price from customers as c,orders as o,orderitems as oi where c.cust_id=o.cust_id and oi.order_num=o.order_num and prod_id='FB';
该实例中,通配符只对第一个表使用。所有其他列明确列出,所以没有重复的列被检索出来。
4、外部联结
联结都是一个表中的行与另一个表中的行相关联。但有时候需要包含那些没有关联行的那些行。LEFT OUTER JOIN ON
RIGHT OUTER JOIN ON
select customers.cust_id,orders.order_num from customers left outer join orders on customers.cust_id=orders.cust_id;
LEFT表示包含其所有行的表(LEFT指出的是OUTER JOIN左边的表)。
5、使用聚集函数的联结
select customers.cust_name, customers.cust_id, count(orders.order_num) as num_ord from customers inner join orders on customers.cust_id=orders.cust_id group by customers.cust_id;
相关文章推荐
- 16 创建高级联结
- 第9天-mysql创建高级联结
- MySQL创建高级联结
- MySQL联结表与创建高级联结表.md
- MYSQL学习笔记(十二)创建高级联结
- MySQL创建联结
- mysql导入导出数据中文乱码解决方法小结(1、navicat导入问题已解决,创建连接后修改连接属性,选择高级->将使用Mysql字符集复选框去掉,下拉框选择GBK->导入sql文件OK;2、phpmyadmin显示乱码的问题也解决,两步:1.将sql文件以utf8的字符集编码另存,2.将文件中sql语句中的字段字符集编码改成utf8,导入OK)
- 读书笔记--SQL必知必会13--创建高级联结
- MySQL高级六——函数创建和使用
- 12.创建高级联结---SQL
- Mysql DBA 高级运维学习笔记-创建Mysql用户及授权的多种方法实战
- SQL必知必会(三) 联结表、创建高级联结、组合查询
- SQL必知必会 笔记 第十三章 创建高级联结
- SQL 必知必会·笔记<11>创建高级联结
- MySQL数据库——创建高级联结
- 第十三课 创建高级联结
- [MYSQL -15]创建联结
- MySQL创建用户与授权方法
- MySQL添加新用户、为用户创建数据库、为新用户分配权限
- mysql学习笔记(2)-创建MySQL索引