Home > Database > Mysql Tutorial > How to Correctly Use the 'NOT IN' Operator in MySQL Queries?

How to Correctly Use the 'NOT IN' Operator in MySQL Queries?

Mary-Kate Olsen
Release: 2025-01-13 14:16:41
Original
767 people have browsed it

How to Correctly Use the

MySQL “NOT IN” conditional query detailed explanation

MySQL database supports the "NOT IN" operator, which is used to retrieve rows from one table whose specified column values ​​do not exist in another table. However, it should be noted that the syntax of "NOT IN" query in MySQL is different from other database systems.

Grammar error analysis

The syntax you are trying to use:

<code class="language-sql">SELECT * FROM Table1 WHERE Table1.principal NOT IN Table2.principal</code>
Copy after login

produces a syntax error because you are trying to compare two columns directly without using a subquery.

Correct syntax for "NOT IN" query

The correct syntax for “NOT IN” query in MySQL is as follows:

<code class="language-sql">SELECT * FROM Table1 WHERE Table1.principal NOT IN (SELECT principal FROM Table2)</code>
Copy after login

In this syntax, we use a subquery to select values ​​from the “principal” column of Table2 and compare these values ​​to the “principal” column of Table1. The result will be a list of rows in Table1 where the "principal" value is not in Table2.

The above is the detailed content of How to Correctly Use the 'NOT IN' Operator in MySQL Queries?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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