Home > Database > Mysql Tutorial > body text

How to Efficiently Select Rows from One Table that Are Not Present in Another Table?

DDD
Release: 2024-10-26 11:49:29
Original
685 people have browsed it

 How to Efficiently Select Rows from One Table that Are Not Present in Another Table?

MySQL Selecting Rows Not Present in Another Table

To obtain all rows that exist in Table A but not in Table B while sharing common primary keys, a few methods are available, with varying performance implications.

Using a Subquery with NOT EXISTS:

Your initial approach with a subquery using NOT EXISTS is a viable option, but can be relatively slow, especially with larger datasets.

Using a Left Join:

As you discovered, a left join can perform faster. When joining Table A with Table B on the shared column, rows in Table A that do not match any rows in Table B will have NULL values in the join column. Filtering for these NULL values effectively isolates the desired rows.

Code Example:

<code class="sql">SELECT *
FROM A
LEFT JOIN B ON A.x = B.y
WHERE B.y IS NULL;</code>
Copy after login

Additional Tips:

  • Ensure proper indexing on the join columns for both tables.
  • Use a covering index on Table B to reduce the number of disk reads.
  • Consider using a UNION query with a negative filter to explicitly exclude rows from Table B.

Overall Conclusion:

While the left join method typically outperforms the subquery approach, the optimal solution may vary depending on the specific dataset and schema. Experimentation and performance testing are recommended to determine the most efficient approach in each situation.

The above is the detailed content of How to Efficiently Select Rows from One Table that Are Not Present 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!