Home >Database >Mysql Tutorial >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):
<code class="language-sql">SELECT name FROM table2 -- that are not in table1 already</code>
Solution:
A more accurate query to get the desired results is:
<code class="language-sql">SELECT t2.name FROM table2 t2 LEFT JOIN table1 t1 ON t1.name = t2.name WHERE t1.name IS NULL;</code>
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:
<code class="language-sql">SELECT name FROM table2 t2 WHERE NOT EXISTS ( SELECT 1 FROM table1 t1 WHERE t1.name = t2.name );</code>
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!