简体   繁体   中英

What's wrong with this MySQL query (uses LEFT OUTER JOIN)?

I'm trying to make a query that returns the following: All users such that: -They are not an admin or owner account -They have the same client_id as the project's client_id -They are not already in the project_users table with entry project_users.project_id = 9

Here is my MySQL query:

SELECT `users`.`id` as id, `users`.`first_name` as first_name, `users`.`last_name` as last_name, `users`.`username` as username
FROM (`users`)
JOIN `projects` ON `projects`.`client_id` = `users`.`client_id` AND projects.id = 9
LEFT OUTER JOIN `project_users` ON `users`.`id` = `project_users`.`user_id`
WHERE `users`.`user_type` != 'Admin'
AND `users`.`user_type` != 'Owner'

For some reason, this query seems to return all non-super(not owner or admin) users with the same client_id as the project, but does NOT exclude those already in the project_users table (ie. the LEFT OUTER JOIN statement isn't working).

Can anyone tell me what is wrong with the query?

Thanks!

You need to add a filter to find the rows that don't match. Also, your query can be helped by using table aliases:

SELECT u.`id` as id, u.`first_name` as first_name, u.`last_name` as last_name, u.`username` as username
FROM `users` u JOIN
     `projects` p
     ON p.`client_id` = u.`client_id` AND p.id = 9 LEFT OUTER JOIN
     `project_users` pu
     ON u.`id` = pu.`user_id`
WHERE u.`user_type` not in ('Admin', 'Owner') and
      pu.user_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