在哪 - 必须满足所有参数

时间:2014-08-18 12:05:54

标签: mysql

我正在进行查询。

这是我的疑问:

select * from `xh_user` 
where (select count(*) 
       from `xh_roles` 
       inner join `xh_role_user` on `xh_roles`.`id` = `xh_role_user`.`role_id` 
       where `xh_role_user`.`user_id` = `xh_user`.`id` 
       and `title` in (?, ?)) >= 1 
and `id` = ? limit 1'

我正在搜索标题符合我的参数的行。

如果满足其中一个参数,行会回来。

我怎样才能使所有参数都得到满足?

2 个答案:

答案 0 :(得分:1)

假设您有两个参数:

select *
from `xh_user` 
where (select count(distinct title) 
       from `xh_roles` inner join
            `xh_role_user`
            on `xh_roles`.`id` = `xh_role_user`.`role_id` 
       where `xh_role_user`.`user_id` = `xh_user`.`id` and
             `title` in (?, ?)
      ) = 2 and
      `id` = ?
limit 1;

答案 1 :(得分:0)

您可以使用连接执行此操作 - 为每个参数添加新的连接条件:

select * 
from `xh_user` 
inner join `xh_role_user`.`user_id` = `xh_user`.`id` 
inner join `xh_roles` as roles on roles.`id` = `xh_role_user`.`role_id` 
                               and title = ? --first title
inner join `xh_roles` as roles2 on roles2.`id` = `xh_role_user`.`role_id` 
                                and title = ? --second title