Home > Database > Mysql Tutorial > How to Select Rows from One Table with No Matching Entries in Another Table?

How to Select Rows from One Table with No Matching Entries in Another Table?

Susan Sarandon
Release: 2025-01-15 17:31:45
Original
434 people have browsed it

How to Select Rows from One Table with No Matching Entries in Another Table?

Find rows that do not have corresponding entries in another table

In the world of database maintenance, ensuring data integrity is crucial, especially when dealing with tables that lack foreign key constraints. Identifying and cleaning up erroneous data is critical to establishing correct relationships between tables.

A common question is: How to construct a query to retrieve rows that do not have corresponding entries in another table?

Consider the following query:

<code class="language-sql">SELECT t1.ID
FROM Table1 t1
LEFT JOIN Table2 t2 ON t1.ID = t2.ID
WHERE t2.ID IS NULL</code>
Copy after login

Instructions:

  • LEFT JOIN: This join type ensures that all rows in Table1 are returned regardless of whether a match is found in Table2.
  • WHERE t2.ID IS NULL: This clause filters the results to include only rows in Table2 with ID NULL. In other words, it returns rows that have no corresponding entries in Table2.

By understanding the basic concepts of joins and NULL values, you can effectively build queries, find erroneous data, and maintain the integrity of your database without having to seek outside help for each affected table.

The above is the detailed content of How to Select Rows from One Table with No Matching Entries in Another Table?. 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