如何在另一张桌子上不存在

时间:2016-08-30 05:42:48

标签: php mysql

如何在这两个表的另一个表上不存在?

Users table enter image description here

User_relationships table

enter image description here

这是我当前的查询

"SELECT * FROM `users` 
WHERE CONCAT(first_name, " ", last_name) LIKE '%' . $name . '%' 
    AND (`role_id` = 6 OR `role_id` = 4)
ORDER BY `first_name` asc limit 15"

我想添加查询guardian_id(user_id)表中不存在user_relationships的查询

更新1

select * from `users` 
    where not exists 
            (select 1 from `user_relationships` 
             inner join `users` on `user_relationships`.`guardian_id` = `users`.`id` 
             where `user_relationships`.`student_id` = 422) 

我试过这个但仍然没有给我零结果。

我只有var name = ?student_id = ?

1 个答案:

答案 0 :(得分:0)

尝试在'DISTINCT'中使用“NOT IN”查询功能。

以下可能对您有帮助。

select * from users where CONCAT(first_name, " ", last_name) LIKE '%' . $name . '%' and (role_id= 6 or role_id= 4) and (id NOT IN (select DISTINCT guardian_id from User_relationships where student_id = $student_id)) order by first_name ASC limit 15

如果您仍需要进行一些更改,请与我们联系。