根据 MySQL 中另外两列的值匹配列值


我们首先创建一个表 −

mysql> create table DemoTable774 (
   Id int,
   FirstName varchar(100),
   MatchId int
);
Query OK, 0 rows affected (0.62 sec)

使用 insert 命令在表中插入一些记录 −

mysql> insert into DemoTable774 values(101,'Chris',104);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable774 values(102,'Adam',103);
Query OK, 1 row affected (0.23 sec)
mysql> insert into DemoTable774 values(103,'Carol',102);
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable774 values(104,'Bob',101);
Query OK, 1 row affected (0.16 sec)

使用 select 语句显示表中的所有记录 −

mysql> select *from DemoTable774;

这将产生以下输出 -

+------+-----------+---------+
| Id   | FirstName | MatchId |
+------+-----------+---------+
|  101 | Chris     |     104 |
|  102 | Adam      |     103 |
|  103 | Carol     |     102 |
|  104 | Bob       |     101 |
+------+-----------+---------+
4 rows in set (0.00 sec)

以下是根据 ID 和 MatchID 显示 FirstName 的查询 −

mysql> select tbl1.FirstName, tbl2.FirstName from DemoTable774 AS tbl1
   left join DemoTable774 AS tbl2 ON( tbl1.MatchId = tbl2.Id );

这将产生以下输出 -

+-----------+-----------+
| FirstName | FirstName |
+-----------+-----------+
| Bob       | Chris     |
| Carol     | Adam      |
| Adam      | Carol     |
| Chris     | Bob       |
+-----------+-----------+
4 rows in set (0.03 sec)

更新于: 2019-09-03

116 浏览

开启你的 职业 生涯

完成课程获取认证

开始
广告