Exclude rows based on column value when another duplicate column value is found in MySQL?


For this, you can use subquery. Let us first create a −

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

Insert some records in the table using insert −

mysql> insert into DemoTable1427 values(201,89);
Query OK, 1 row affected (0.13 sec)
mysql> insert into DemoTable1427 values(201,99);
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable1427 values(210,98);
Query OK, 1 row affected (0.16 sec)

Display all records from the table using select −

mysql> select * from DemoTable1427 ;

This will produce the following output −

+-----------+--------------+
| StudentId | StudentMarks |
+-----------+--------------+
|       201 |           89 |
|       201 |           99 |
|       210 |           98 |
+-----------+--------------+
3 rows in set (0.00 sec)

Here is the query to exclude rows based on column value when another duplicate column value is found. Here, Studentmarks 89 is with StudentId 201 and with that Studentid 201 is also having another record, therefore both will get excluded from the result −

mysql> select * from DemoTable1427
   -> where StudentId NOT IN (select distinct StudentId from DemoTable1427 where StudentMarks=89);

This will produce the following output −

+-----------+--------------+
| StudentId | StudentMarks |
+-----------+--------------+
|       210 |           98 |
+-----------+--------------+
1 row in set (0.00 sec)

Updated on: 12-Nov-2019

361 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements