mysql求兩個表的不同記錄

來源:互聯網
上載者:User

問題是:現在有兩個表,一個是記錄昨天的記錄,一個是記錄今天的記錄,如何求

(1)新增的記錄:今天有,昨天沒有的記錄;

(2)減少的記錄:今天沒有,昨天有的記錄;

求解該類問題,需要用到sql的串連查詢。

為了簡單起見,使用user1表和user2表來進行儲存昨天的記錄和今天的記錄

CREATE   TABLE   test4.user1 (    id   int   NOT   NULL,    name   varchar(20)   NOT   NULL,    PRIMARY   KEY   (id));

然後更新表,得到如下結果

昨天的記錄存在user1表:

昨天的記錄存在user2表:

新增的記錄:

select test4.user2.id,test4.user2.namefrom test4.user1 right outer join test4.user2on test4.user1.id = test4.user2.idwhere test4.user1.id is null;

運行結果:



減少的記錄:

select test4.user1.id, test4.user1.namefrom test4.user1 left outer join test4.user2on test4.user1.id = test4.user2.idwhere test4.user2.id is null;



補充知識點:

inner join,full outer join,left join,right jion
內部串連 inner join 兩表都滿足的組合
full outer 全連 兩表相同的組合在一起,A表有,B表沒有的資料(顯示為null),同樣B表有
A表沒有的顯示為(null)
A表 left join B表 左連,以A表為基礎,A表的全部資料,B表有的組合。沒有的為null
A表 right join B表 右連,以B表為基礎,B表的全部資料,A表的有的組合。沒有的為null

http://lhx1026.iteye.com/blog/512776

http://database.51cto.com/art/201011/234342.htm

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 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.