How to return rows that have the same column values in MySQL?

MySQLMySQLi Database

Use GROUP BY clause for this. Let us first create a table −

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

Insert some records in the table using insert command −

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)

Display all records from the table using select statement −

mysql> select *from DemoTable;

Output

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

Here is the query to return rows that have the same column values in MySQL −

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

Output

+--------------+
| StudentMarks |
+--------------+
| 58           |
+--------------+
1 row in set (0.00 sec)
raja
Published on 10-Jul-2019 11:20:44
Advertisements