duangai9678 2014-01-08 21:09
浏览 153
已采纳

这个MySQL查询有什么问题(使用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!

  • 写回答

1条回答 默认 最新

  • duanjizhan9353 2014-01-08 21:12
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在获取boss直聘的聊天的时候只能获取到前40条聊天数据
  • ¥20 关于URL获取的参数,无法执行二选一查询
  • ¥15 液位控制,当液位超过高限时常开触点59闭合,直到液位低于低限时,断开
  • ¥15 marlin编译错误,如何解决?
  • ¥15 有偿四位数,节约算法和扫描算法
  • ¥15 VUE项目怎么运行,系统打不开
  • ¥50 pointpillars等目标检测算法怎么融合注意力机制
  • ¥20 Vs code Mac系统 PHP Debug调试环境配置
  • ¥60 大一项目课,微信小程序
  • ¥15 求视频摘要youtube和ovp数据集