sql中连接的几种方式

use MyTestSQL
   create table T_Customer(保存的是客户的信息)(
   FId int not null,
   FName varchar(20) not null,(客户的姓名)
   FAge int,(客户的年龄)
   primary key(FId)
   )
   create table T_OrderType(订单的类型)(
   FId int not null,
   FName varchar(20)not null,(类型的名称)
   primary key(FId)
   )
  
   create table T_Order(订单的信息)(
   FId int not null,
   FNumber varchar(20) not null,(订单的号码)
   FPrice numeric(10,2),(订单的价格)
   FCustomerId int,(客户的主键)
   FTypeId int,(订单类型的主键)
   primary key(FId)
   )
  

 

 

 

 

 

表连接的简介:

在我们写实际的项目的时候,我们需要从多张表中选择数据,所以表连接也是一个蛮重要的问题,表连接的关键字是JOIN

例子:

查找姓名为Mike的客户的订单号和票价

select FId from T_Customer where Fname='MIKE'
SELECT Fnumber,FPrice FROM T_Order WHERE FCustomerId = 2;

上述的两条SQL语句效率是相当的低下,所以就使用表的连接来查询数据的话效率会高。

内连接(INNER JOIN):

内连接的时候需要指出用那些字段来实现关联

上述的两条SQL语句可以这样写:

select o.Fnumber ,o.FPrice from T_Order o inner join T_Customer c on c.FId=o.FCustomerId where c.FName='Mike';

在大多数的数据库系统中默认的连接方式是内连接。

 

 

 不等值的链接:

select T_order.FNumber,T_Order.FPrice,T_Customer.FName,T_Customer.FAge from T_Order join T_Customer on T_Order.FPrice < T_Customer.FAge*5 and T_Order.FCustomerId = T_Customer.FId;

 

右连接:

select o.FNumber,o.FPrice,o.FCustomerId,c.FName,c.FAge from T_Order o left outer join T_Customer c on o.FCustomerId = c.FId union select o.FNumber,o.FPrice,o.FCustomerId,c.FName,c.FAge from T_Order o right outer join T_Customer c on o.FCustomerId = c.FId;

 

 

全连接:

select o.FNumber,o.FPrice,o.FCustomerId,c.FName,c.FAge from T_Order o full outer join T_Customer c on o.FCustomerId = c.FId;

 

 

在mysql中是不支持全链接的,可以用union这个关键字来实现全链接

 

select o.FNumber,o.FPrice,o.FCustomerId,c.FName,c.FAge from T_Order o left outer join T_Customer c
on o.FCustomerId = c.FId
union
select o.FNumber,o.FPrice,o.FCustomerId,c.FName,c.FAge from T_Order o right outer join T_Customer c
on o.FCustomerId = c.FId;

 

 

 

 

 

 

 

 

 

 

 

 


  
  
  
  
  
  
  

posted on 2015-08-13 22:34  aicpcode  阅读(680)  评论(0编辑  收藏  举报

导航