Home > Database > Mysql Tutorial > How to Exclude Rows in MySQL Queries Without EXCEPT?

How to Exclude Rows in MySQL Queries Without EXCEPT?

Patricia Arquette
Release: 2025-01-01 12:05:10
Original
880 people have browsed it

How to Exclude Rows in MySQL Queries Without EXCEPT?

EXCEPT Syntax Error in SQL Query

In MySQL, using the EXCEPT syntax to exclude rows from a query can result in a syntax error. This is because MySQL doesn't natively support the EXCEPT keyword.

Alternative Solutions

To achieve the desired exclusion functionality, you can use either the NOT IN clause or a LEFT JOIN with an IFNULL condition:

NOT IN Clause:

SELECT s.sno
FROM students s
WHERE s.sno NOT IN (
    SELECT t.sno
    FROM take t
    WHERE t.cno = 'CS112'
);
Copy after login

LEFT JOIN with IFNULL:

SELECT s.sno
FROM students s
LEFT JOIN take t ON s.sno = t.sno
WHERE IFNULL(t.cno, '') != 'CS112';
Copy after login

Example

Consider the following sample data:

create temporary table students (sno int);

insert into students values (1);
insert into students values (2);
insert into students values (3);
insert into students values (4);
insert into students values (5);
insert into students values (6);
insert into students values (7);
insert into students values (8);
insert into students values (9);
insert into students values (10);

create temporary table take (sno int, cno varchar(50));

insert into take values (1, 'CS112');
insert into take values (2, 'CS112');
insert into take values (3, 'CS112');
insert into take values (4, 'CS112');
Copy after login

Using either the NOT IN clause or the LEFT JOIN with IFNULL will return the following result:

+------+
| sno  |
+------+
|    5 |
|    6 |
|    7 |
|    8 |
|    9 |
|   10 |
+------+
Copy after login

These alternative methods effectively exclude students who have taken the course CS112, resulting in a list of students who haven't taken the course.

The above is the detailed content of How to Exclude Rows in MySQL Queries Without EXCEPT?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template