MS-SQL中的三種聯結與合并(舉例說明)的區別的HOWTO文章,

來源:互聯網
上載者:User

MS-SQL中的三種聯結與合并(舉例說明)的區別的HOWTO文章,

測試平台:MS-SQL 2008 R2 ;

下面將以兩個t_a和t_b表來測試聯結和全並

第一:建立A表

create table t_a([aid] [int],[anum]  [char])


第二:建立B表

create table t_b([bid] [int],[aname]  [char])


第三:1:在A表中添加資料

insert INTO t_a(aid,anum) SELECT 1,20050111 unionselect 2,20050112 unionselect 3,20050113 unionselect 4,20050114union ALL SELECT 5,20050115


A表資料如下

aid  anum

1   20050111

2   20050112

3   20050113

4   20050114

5   20050115

 

2:給B表添加資料

insertINTO t_b(bid,bname) SELECT 1,2006032401 unionselect 2,2006032402 unionselect 3,2006032403 unionselect 4,2006032404union ALL SELECT 8,2006032408


B表資料如下

bid bname

1   2006032401

2   2006032402

3   2006032403

4   2006032404

8   2006032408

第四:1:左聯結如下

select * from t_a left join t_b on t_a.aid=t_b.bid


左聯結資料如下

aid anum     bid bname

1   20050111   1   2006032401

2   20050112   2   2006032402

3   20050113   3   2006032403

4   20050114   4   2006032404

5   20050115   NULL   NULL

2:右聯結如下

select * from t_a right join t_b on t_a.aid=t_b.bid


右聯結資料顯示如下

aid anum    bid bname

1   20050111   1   2006032401

2   20050112   2   2006032402

3   20050113   3   2006032403

4   20050114   4   2006032404

NULL   NULL   8   2006032408

總結:1:join前的表排列在前面,join後的表在後面;

2:左聯是以左右的資料為準,右聯是以右邊的資料為準;

3:Inner join如下

select * from t_a inner join t_b on t_a.aID = t_b.bID


顯示如下:

aid anum       bid bname

1   20050111   1   2006032401

2   20050112   2   2006032402

3   20050113   3   2006032403

4   20050114   4   2006032404

總結:inner join與 right join和leftjoin的區別;只顯示 aid=bid行數,其它則不用顯示;

合并t_a和t_b這兩個表

select * from t_bunionselect * from t_a


bid bname

1   20050111

1   2006032401

2   20050112

2   2006032402

3   20050113

3   2006032403

4   20050114

4   2006032404

5   20050115

8   2006032408

合并與聯結的差別

1:合并是縱向相加;不過是相對行的行顯示成兩行;

2:聯結是橫向加想;只是以左邊要麼右邊的資料而已;

注意:我在這個過程中出現的一些操作另外總結

一:當刪有兩例的資料的時候要用一個and

delete  from t_a where aid='1' and anum='20050111'


二:修改一個例表的例名

1:刪除一個表的name列

alter table t_bdrop colum aname 


2:新增一個表中的bname列

alter table t_badd bname int


 三:象a12345這樣列的資料定義類型(後面那個有含有5的括弧的應該與在中括弧外不能寫在裡面)

create table t_test ( [id] [char](5)  )


相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.