選擇某列在多條記錄中包含相同資料的 MySQL 行?


使用 MySQL JOIN 選擇某列在多條記錄中包含相同資料的 MySQL 行。我們首先建立一個表 −

mysql> create table DemoTable
(
   UserId int,
   UserName varchar(20)
);
Query OK, 0 rows affected (0.54 sec)

使用 insert 命令在表中插入記錄 −

mysql> insert into DemoTable values(10,'John');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(11,'Sam');
Query OK, 1 row affected (0.21 sec)
mysql> insert into DemoTable values(12,'Larry');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable values(13,'David');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values(14,'Larry');
Query OK, 1 row affected (0.10 sec)

使用 select 命令從表中顯示記錄 −

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)

更新於: 30-Jul-2019

487 次瀏覽

開啟你的 職業 生涯

完成課程並獲得認證

開始使用
廣告
© . All rights reserved.