MySQL表連接自身

來源:互聯網
上載者:User

MySQL資料庫不僅可以在表與表之間連接,而且還能讓其自身連接,這個功能不能不說是很讓人舒服的了。下面我們就來看看在mysql中怎麼讓表連接自身。
  
      假如在MySQL中建立一個表
       create table d
                    (
                     id int(10) auto_increment primary key not null,
                     name char(20) not null,
                     sex varchar(10) not null,
                     birth date default null
                   )type=myisam default charset=gbk;

 現在我們插入一些資料到d表中
                        INSERT INTO `d` (`id`, `name`, `sex`, `birth`) VALUES
                                                  (1, 'Gwen', 'm', '1989-03-17'),
                                                  (2, 'Harold', 'f', '1989-05-13'),
                                                  (3, 'Fang', 'm', '1990-08-27'),
                                                  (4, 'iane', 'm', '1979-08-31'),
                                                  (5, 'Gwens', 'f', '1988-09-11'),
                                                  (6, 'wen', 'f', '1988-08-03');


    下面我們要在d表中找出異性且年齡差距不超過4歲,這裡就要用到表連接了:
      具體語句如下:
      select p1.name,p2.name,p1.sex,p2.sex,p1.birth,p2.birth from d as p1,d as p2 where p1.sex='f' and p2.sex='m' and (((year(p1.birth)-year(p2.birth))-(right(p1.birth,5)<right(p2.birth,5)))<4 or ((year(p1.birth)-year(p2.birth))-(right(p1.birth,5)<right(p2.birth,5)))>-4);
   具體的文法可見mysql手冊,裡面講得很詳細。
得到的是: 

 
name name sex sex birth birth
Harold Gwen f m 1989-05-13 1989-03-17
Gwens Gwen f m 1988-09-11 1989-03-17
wen Gwen f m 1988-08-03 1989-03-17
Harold Fang f m 1989-05-13 1990-08-27
Gwens Fang f m 1988-09-11 1990-08-27
wen Fang f m 1988-08-03 1990-08-27
Harold iane f m 1989-05-13 1979-08-31
Gwens iane f m 1988-09-11 1979-08-31
wen iane f m 1988-08-03 1979-08-31

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.