SQL Query查找缺少的角色

时间:2017-08-01 11:31:59

标签: mysql sql

我试图编写一个SQL查询来查找缺少admin角色的公司。下面是表格设计,查询应返回值2,因为公司2没有与之关联的管理员角色。

表信息 - 公司,CompanyRoleMapping(请假设公司3,4具有所有5个角色)

我试过了这个查询

Select Company.COMPANY_ID
from Company inner join
     CompanyRoleMapping
     on Company.COMPANY_ID = CompanyRoleMapping.COMPANY_ID
group by USER_ROLE
having CompanyRoleMapping.USER_ROLE = 'admin'

enter image description here

但它似乎不起作用。能帮助我吗

4 个答案:

答案 0 :(得分:1)

<div id="form-wrapper"> <label for="username">UserName </label> <input type="text" id="username" name="myuser" onkeyup="Validation()"/><span class="validation" id="demo1"> </span> <br/> <br/> <label for="password"> Password </label> <input type="password" id="password" name="mypassword" onkeyup="Validation()" /> <span class="validation" id="demo2"> </span> <br /> <input type="submit" id="login" value="Log in" onclick="return Validation()" /> <br /> <input type="checkbox" checked="checked" /> Remember me </div>子句

中选择ID
WHERE

公司

SELECT c.COMPANY_ID
FROM company c
WHERE c.COMPANY_ID NOT IN (SELECT crm.COMPANY_ID FROM CompanyRoleMapping crm WHERE crm.USER_ROLE = 'admin')

CompanyRoleMapping

Company_ID
1
2
3
4

输出

Company_id user_role
1          admin
1          manager
1          employee
1          client
1          technician
2          manager
2          employee
2          client
2          technician

SQL小提琴:http://sqlfiddle.com/#!9/c07c28/1/0

没有子查询

COMPANY_ID
2

输出

SELECT c.COMPANY_ID
FROM company c
INNER JOIN CompanyRoleMapping crm ON c.COMPANY_ID != crm.COMPANY_ID and crm.USER_ROLE = 'admin'

SQL小提琴:http://sqlfiddle.com/#!9/c07c28/5/0

答案 1 :(得分:0)

可能这个SQL在更大的表上会更快:

 

<div id="summary"><div id="container"></div>
		<div id="blocker"></div>
				<script type ="text/javascript" src="user.js"></script>   
</div>
		
<button type="button">Personal</button>
					<a href="#" onclick="f1(1);"<button type="button">Apps</button></a>
					<button type="button" >Settings</button>

答案 2 :(得分:0)

试试这个: -

SELECT C.* FROM Company C
WHERE C.CompanyID NOT IN 
  (
    SELECT CRM.CompanyID FROM CompanyRoleMapping CRM
    WHERE CRM.UserRole = 'admin'
  )

答案 3 :(得分:0)

您可以尝试此查询:

SELECT C.COMPANY_ID, GROUP_CONCAT(CM.USER_PROFILE) AS `profiles` FROM `Company` AS C INNER JOIN `CompanyRoleMapping` AS CM ON C.COMPANY_ID = CM.COMPANY_ID
GROUP BY C.COMPANY_ID
HAVING (CASE WHEN `profiles` NOT LIKE '%admin%' THEN 1 ELSE 0 END) = 1;

SQL小提琴:http://sqlfiddle.com/#!9/6becc1/6