Home > Database > Mysql Tutorial > How to Select Rows from One MySQL Table That Are Not in Another?

How to Select Rows from One MySQL Table That Are Not in Another?

Linda Hamilton
Release: 2024-12-27 06:57:12
Original
645 people have browsed it

How to Select Rows from One MySQL Table That Are Not in Another?

Selecting Rows not Present in Another Table: A Guide for MySQL Queries

The task at hand involves extracting all rows from one table (Table1) that are not present in another (Table2). To accomplish this, we employ a specific syntax in MySQL, catering to the unique nature of the task.

In contrast to using the asterisk (*) symbol, which retrieves all columns in a query, you must specify the exact column(s) involved in the comparison between the two tables. For instance, if both tables share a common column named "id," the following query will effectively retrieve the desired result:

SELECT * FROM Table1 WHERE id NOT IN (SELECT id FROM Table2)
Copy after login

This query leverages a subquery, enclosed in parentheses, to retrieve the distinct values of the id column from Table2. The main query subsequently filters Table1 to exclude any rows where the id value already exists in the subquery result.

Remember to use the appropriate column name(s) in your specific use case. Consult the MySQL subquery documentation for further insights and additional examples to handle various scenarios involving data extraction and manipulation.

The above is the detailed content of How to Select Rows from One MySQL Table That Are Not in Another?. 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