如何使用 MySQL 查詢一列或多列具有相同值的記錄?


為此,你可以使用帶有子查詢的 GROUP BY HAVING。我們首先建立一個表−

mysql> create table DemoTable1861
     (
     Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
     Name varchar(20),
     Marks int
     );
Query OK, 0 rows affected (0.00 sec)

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

mysql> insert into DemoTable1861(Name,Marks) values('John',45);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1861(Name,Marks) values('Chris',74);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1861(Name,Marks) values('David',89);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1861(Name,Marks) values('Chris',74);
Query OK, 1 row affected (0.00 sec)
mysql> insert into DemoTable1861(Name,Marks) values('John',49);
Query OK, 1 row affected (0.00 sec)

使用 select 語句從表中顯示所有記錄 −

mysql> select * from DemoTable1861;

這將生成以下輸出 −

+----+-------+-------+
| Id | Name  | Marks |
+----+-------+-------+
|  1 | John  |    45 |
|  2 | Chris |    74 |
|  3 | David |    89 |
|  4 | Chris |    74 |
|  5 | John  |    49 |
+----+-------+-------+
5 rows in set (0.00 sec)

這裡是如何查詢一列或多列中具有相同值的記錄

mysql> select Id,Name,Marks from DemoTable1861
     where (Name,Marks) IN ( select Name,Marks from DemoTable1861
     group by Name,Marks
     having count(*) > 1);

這將生成以下輸出 −

+----+-------+-------+
| Id | Name  | Marks |
+----+-------+-------+
|  2 | Chris |    74 |
|  4 | Chris |    74 |
+----+-------+-------+
2 rows in set (0.00 sec)

更新於: 2019-12-26

376 次瀏覽

開啟您的 職業

透過完成課程獲得認證

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