如何在MySQL中使用SELF JOIN?

如何在MySQL中使用SELF JOIN?

要使用SELF JOIN,让我们创建一个表。创建表的查询如下-

mysql> create table SelfJoinDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> CountryName varchar(20),
   -> CountryRank int,
   -> `Year` varchar(10)
   -> );
Query OK, 0 rows affected (1.02 sec)

现在,您可以使用插入命令在表中插入一些记录。查询如下-

mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('US',1,'2016');
Query OK, 1 row affected (0.12 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('UK',5,'2013');
Query OK, 1 row affected (0.16 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('France',45,'2010');
Query OK, 1 row affected (0.21 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('Turkey',3,'2000');
Query OK, 1 row affected (0.17 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('Japan',78,'1995');
Query OK, 1 row affected (0.21 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('Romania',110,'2007');
Query OK, 1 row affected (0.22 sec)
mysql> insert into SelfJoinDemo(CountryName,CountryRank,`Year`) values('UK',3,'2000');
Query OK, 1 row affected (0.16 sec)

使用select语句显示表中的所有记录。查询如下-

mysql> select *from SelfJoinDemo;

以下为输出结果-

+----+-------------+-------------+------+
| Id | CountryName | CountryRank | Year |
+----+-------------+-------------+------+
|  1 | US          |           1 | 2016 |
|  2 | UK          |           5 | 2013 |
|  3 | France      |          45 | 2010 |
|  4 | Turkey      |           3 | 2000 |
|  5 | Japan       |          78 | 1995 |
|  6 | Romania     |         110 | 2007 |
|  7 | UK          |           3 | 2000 |
+----+-------------+-------------+------+
7 rows in set (0.00 sec)

以下是SELF JOIN的查询-

mysql> SELECT DISTINCT t1.CountryName, t2.Year
   -> FROM SelfJoinDemo AS t1,
   -> SelfJoinDemo AS t2
   -> WHERE t1.Year=t2.Year
   -> and t1.CountryName='US';

以下为输出结果-

+-------------+------+
| CountryName | Year |
+-------------+------+
| US          | 2016 |
+-------------+------+
1 row in set (0.00 sec

阅读更多:MySQL 教程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程