Home > Database > Mysql Tutorial > How to Select Records from Table2 Excluding Those with Matching Names in Table1?

How to Select Records from Table2 Excluding Those with Matching Names in Table1?

Susan Sarandon
Release: 2025-01-19 16:46:15
Original
639 people have browsed it

How to Select Records from Table2 Excluding Those with Matching Names in Table1?

Select from one table to exclude records from another table

Question:

Given two tables, table1 contains columns id and name, table2 contains columns id and name, retrieve all rows in table2 whose name value is not in table1.

Suggested query (incorrect):

SELECT name
FROM table2
-- that are not in table1 already
Copy after login

Solution:

A more accurate query to get the desired results is:

SELECT t2.name
FROM table2 t2
LEFT JOIN table1 t1 ON t1.name = t2.name
WHERE t1.name IS NULL;
Copy after login

Explanation:

This query uses a left join to match each row in table2 to the corresponding row in table1 based on the name column. If a matching row is not found in table1, the t1.name value for that row in the results will be NULL. By selecting only those rows where t1.name is NULL, we effectively exclude records in table2 that have matching name values ​​in table1. Alternatively, the NOT EXISTS clause can be used to achieve the same result:

SELECT name
FROM table2 t2
WHERE NOT EXISTS (
    SELECT 1
    FROM table1 t1
    WHERE t1.name = t2.name
);
Copy after login

The NOT EXISTS version is generally more efficient than the LEFT JOIN version, especially on large datasets.

The above is the detailed content of How to Select Records from Table2 Excluding Those with Matching Names in Table1?. 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