1. 程式人生 > >mysql中union、union all的用法例項

mysql中union、union all的用法例項

1、建表資料:

create table a(fname varchar(30),lname varchar(30),addr varchar(30))
insert into a values ("a_fname1","a_lname1","a_addr1");
insert into a values ("a_fname2","a_lname2","a_addr2");
insert into a values ("a_fname3","a_lname3","a_addr3");
insert into a values ("test","test","test");

create table
b(last_name varchar(30),first_name varchar(30),address varchar(30));
insert into b values ("b_lastanme1","b_firstname1","b_address1"); insert into b values ("b_lastanme2","b_firstname2","b_address2"); insert into b values ("b_lastanme3","b_firstname3","b_address3"); insert into b values ("test","test"
,"test");
create table c(company varchar(30),street varchar(30)); insert into c values ("c_company1","c_street1"); insert into c values ("c_company2","c_street2"); insert into c values ("c_company3","c_street3");

2、測試結果:

  • 在表a和表b中有兩條重複的資料,如果使用union則是不顯示重複的資料,使用union all則顯示重複的資料,下圖為使用union,共10條資料:
    這裡寫圖片描述

  • 下圖為只是用一個union all,也是不顯示重複的資料,共10條資料:
    這裡寫圖片描述

  • 使用兩個union all顯示重複的資料,共11條資料:
    這裡寫圖片描述