MySQL table join itself

Source: Internet
Author: User

MySQL Databases can not only be joined between tables, but also can be joined by themselves. This function is quite comfortable. Let's take a look at how to make the table join itself in mysql.

Create a table in 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;

Now we insert some data to table d.
Insert into 'D' ('id', 'name', 'sex', 'birth') VALUES
(1, 'gwen ', 'M', '2017-03-17 '),
(2, 'harold ', 'F', '2017-05-13 '),
(3, 'fang ', 'M', '2017-08-27 '),
(4, 'iane ', 'M', '2017-08-31 '),
(5, 'gwens', 'F', '2017-09-11 '),
(6, 'wen', 'F', '2017-08-03 ');


In table d, we need to find out the opposite sex and the age gap is no more than 4 years old. here we need to use table join:
The statement is as follows:
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 );
The specific syntax can be found in the mysql manual, which is detailed.
The result is:

 
Name sex 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.