選擇某列在多條記錄中包含相同資料的 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)
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP