简体   繁体   中英

In mysql how can I get only rows from one table which do not link to any rows in another table with a specific ID

I have two tables with the following structures (unnecessary columns trimmed out)

-----------------   ---------------------
| mod_personnel |   | mod_skills        |
|               |   |                   |
| - prs_id      |   | - prs_id          |
| - name        |   | - skl_id          |
-----------------   |                   |
                    ---------------------

There may be 0 to many rows in the skills table for each prs_id

What I want is all the personnel records which do NOT have an associated skill record with skill_id 1. In plain English "I want all the people who do not have the skill x".

Currently, I have only been able to do it with the following nested select . But I am hoping to find a faster way.

SELECT * FROM `mod_personnel` WHERE `prs_id` NOT IN (
SELECT `prs_id` FROM `mod_skills` WHERE `skl_id` = 1 )

Using a NOT EXISTS might be faster.

SELECT *
       FROM `mod_personnel` p
       WHERE NOT EXISTS (SELECT * 
                                FROM `mod_skills` s
                                WHERE s.`prs_id` = p.`prs_id`
                                      AND s.`skl_id` = 1 );

This may be faster:

SELECT `mod_personnel`.* 
FROM `mod_personnel` 
    left outer join `mod_skills`
        on `mod_skills`.`prs_id` = `mod_personnel`.`prs_id` 
            and `mod_skills`.`skl_id` = 1
WHERE  `mod_skills`.`prs_id` is null;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM