SQL server从入门精通----表的复制与多表连接查询

--select into table2 from table1
--insert into  table2 select table1  讲解

create table userInformation
(
    id int identity(10001,1),
    uid int,
    name nvarchar(30),
    age int,
    birthday nvarchar(30),
    address nvarchar(50),
    country nvarchar(20),
    province nvarchar(20),
    city nvarchar(20),
    remark nvarchar(200),
    --constraint DF_uid Foreign key(uid) references Q_user(uid)
)
select * from userInformation
alter table userInformation
add constraint DF_uid Foreign key(uid) references Q_user(uid)

--将 Q_user 查询的当作表赋值给表(含结构和数据) userInformation(要求此表不存在)
select uid,uName into userInformation from Q_user 
 
--将Q_user查询的数据插入到 userInformation
insert into  userInformation(uid,name) select uid,uName from Q_user

--多表查询

--全连接
select *  
from userInformation,Q_user 

--内连接
select *  
from Q_user b,userInformation a
where a.uid=b.uid 

--内连接(两张 表向中间连接,只要相同的)
select * from Q_user a
inner join userInformation b   --inner 可以省略
on a.uId=b.uid


--左连接   (以左边的表为基础,连接右边有连接数据,没有为null)
select * from Q_user a
left join userInformation b   --inner 可以省略
on a.uId=b.uid

--右连接(以右边的表为基础)
select * from Q_user a
right join userInformation b   --inner 可以省略
on a.uId=b.uid

--自连接(就是连接自己 给一张表取不同的别名就好了)
select * from Q_user a
right join Q_user b   --inner 可以省略
on a.uId=b.uid

----------------union--------
--union 联合两张表的数据,相同数据只显示其中的一条
--union all 完全将两张表联合,不管数据的相同
--不管是union还是union all,前表与后表的列名一定要是一致的,而且不能出现text的列-----------------

select * from Q_user union select * from Q_user  

select * from Q_user union all select * from Q_user 

 

posted @ 2015-09-13 23:53  code_killer  阅读(253)  评论(0编辑  收藏  举报