Home > Database > Mysql Tutorial > How to Correctly Retrieve Missing Data Using `SELECT * WHERE NOT EXISTS`?

How to Correctly Retrieve Missing Data Using `SELECT * WHERE NOT EXISTS`?

Patricia Arquette
Release: 2024-11-26 15:34:10
Original
777 people have browsed it

How to Correctly Retrieve Missing Data Using `SELECT * WHERE NOT EXISTS`?

Retrieve Missing Data Using "SELECT * WHERE NOT EXISTS"

Problem:

To retrieve data from a table where certain cells are not present in another table, a user implemented the following query:

SELECT * from employees WHERE NOT EXISTS (SELECT name FROM eotm_dyn)
Copy after login

However, this query returns no results, despite known missing data.

Solution:

To address the issue, it is necessary to join the two tables based on a common key, such as employeeID. Using NOT EXISTS without a join will always yield no results if the second table contains any data.

The correct query, assuming employeeID is the joining key, is:

SELECT  *
FROM    employees e
WHERE   NOT EXISTS
        (
        SELECT  null 
        FROM    eotm_dyn d
        WHERE   d.employeeID = e.id
        )
Copy after login

Alternatively, a less efficient approach would be to use a LEFT JOIN and filter out the NULL values.

The above is the detailed content of How to Correctly Retrieve Missing Data Using `SELECT * WHERE NOT EXISTS`?. 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