简体   繁体   English

Mysql 在同一表中使用多个 AND 条件的 INNER JOIN 查询

[英]Mysql INNER JOIN query with multiple AND condition in same table

Inner join query I have 2 table user_info and user_role_info .内连接查询我有 2 个表user_infouser_role_info I want to select those user who are in role_id 1 and also at least 1 of the role_id 2 to 4.我想要 select role_id 1 中的那些用户以及 role_id 2 到 4 中的至少 1 个用户。

What I tried我试过的

SELECT * FROM `user_info` a 
INNER JOIN `user_role_info` r ON r.`user_id` = a.`user_id`
WHERE  r.`role_id`= 1 AND r.`role_id` BETWEEN 2 AND 7 GROUP BY a.id
HAVING COUNT(*) > 1; 

From the picture user_id 1 & 2 should be the correct result & user_id 4 should not in the result.从图片中 user_id 1 & 2 应该是正确的结果 & user_id 4 不应该在结果中。 But this query doesn't provide me the correct result.但是这个查询并没有为我提供正确的结果。

You should be asserting the role IDs in the HAVING clause.您应该在HAVING子句中断言角色 ID。 Something like the following should work:像下面这样的东西应该工作:

SELECT a.user_id
FROM user_info a 
INNER JOIN user_role_info r
    ON r.user_id = a.user_id
GROUP BY a.user_id
HAVING SUM(r.role_id = 1) > 0 AND
       SUM(r.role_id IN (2, 3, 4, 5, 6, 7)) > 0;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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