使用MySQL JOIN选择MySQL行,其中的列包含多个记录中的相同数据。让我们首先创建一个表-
mysql> create table DemoTable ( UserId int, UserName varchar(20) );
使用插入命令在表中插入记录-
mysql> insert into DemoTable values(10,'John'); mysql> insert into DemoTable values(11,'Sam'); mysql> insert into DemoTable values(12,'Larry'); mysql> insert into DemoTable values(13,'David'); mysql> insert into DemoTable values(14,'Larry');
使用选择命令显示表中的记录-
mysql> select *from DemoTable;
这将产生以下输出-
+--------+----------+ | UserId | UserName | +--------+----------+ | 10 | John | | 11 | Sam | | 12 | Larry | | 13 | David | | 14 | Larry | +--------+----------+ 5 rows in set (0.00 sec)
以下是查询以选择行,其中一列包含多个记录中的相同数据-
mysql> SELECT DISTINCT tbl1.* FROM DemoTable tbl1 JOIN DemoTable tbl2 on tbl2.UserId <> tbl1.UserId AND tbl2.UserName=tbl1.UserName;
这将产生以下输出-
+--------+----------+ | UserId | UserName | +--------+----------+ | 14 | Larry | | 12 | Larry | +--------+----------+ 2 rows in set (0.14 sec)