如何在 MySQL 中返回具有相同列值的行?

mysqlmysqli database更新于 2025/9/11 8:12:17

为此使用 GROUP BY 子句。让我们首先创建一个表 −

mysql> create table DemoTable
   -> (
   -> StudentId int,
   -> StudentMarks int
   -> );
Query OK, 0 rows affected (4.71 sec)

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

mysql> insert into DemoTable values(23,58);
Query OK, 1 row affected (0.70 sec)

mysql> insert into DemoTable values(25,89);
Query OK, 1 row affected (0.46 sec)

mysql> insert into DemoTable values(26,58);
Query OK, 1 row affected (1.13 sec)

mysql> insert into DemoTable values(28,98);
Query OK, 1 row affected (0.86 sec)

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

mysql> select *from DemoTable;

输出

+-----------+--------------+
| StudentId | StudentMarks |
+-----------+--------------+
| 23        | 58           |
| 25        | 89           |
| 26        | 58           |
| 28        | 98           |
+-----------+--------------+
4 rows in set (0.00 sec)

以下查询用于返回 MySQL 中具有相同列值的行 −

mysql> select StudentMarks from DemoTable
   -> group by StudentMarks
   -> having sum(StudentId=23) > 0 and
   -> sum(StudentId=26) > 0;

输出

+--------------+
| StudentMarks |
+--------------+
| 58           |
+--------------+
1 row in set (0.00 sec)

相关文章


有用资源