2014-02-10 112 views
-1

我需要一些帮助,请:)查询在多对多的关系

ACCOUNTS 
- account_id 
- username 
- password 

USER_RIGHTS 
- rights_id 
- description 
- level 

有多对多的关系(所以我需要一个第三个表) 的USER_RIGHTS包含这些valuse :

1,'READ_ACCOUNTS',0 
2,'CREATE_ACCOUNTS',1 
3,'UPDATE_ACCOUNTS',2 
4,'DELETE_ACCOUNTS',3 
5,'READ_ORDERS',0 
6,'CREATE_ORDERS',1 
7,'UPDATE_ORDERS',2 
8,'DELETE_ORDERS',3 

我需要: - 一个查询,返回所有帐户没有删除任何权- 返回拥有最大用户权限数的所有帐户的查询

谢谢!

+1

那么,这不是“我们为你做你的工作”网站。显示你已经尝试了什么,以及问题出在哪里。从 – fancyPants

+0

选择a.username账户 左外连接ACCOUNTS_RIGHTS AR上a.account_id = ar.account_id 左外连接USER_RIGHTS乌尔上ar.rights_id = ur.rights_id 其中ur.rights_id不是(4,8) 组由a.username 这是为第一个查询 - 但例如在ACCOUNTS_RIGHTS如果我有用户1 - 权利1和用户1 - 权利4它会返回它,我不希望:| – alex1111

回答

0
CREATE TABLE accounts_2_user_rights 
(
    id int 
    account_id int 
    rights_id int 
) 

-- all without delete right 
select * 
from accounts acc 
where not exists 
(
    select 1 
    from rights_user ru 
    inner join accounts_2_user_rights a2ur 
    on a2ur.rights_id = ru.rights_id 
    and a2ur.account_id = acc.account_id 
    where ru.description like 'DELETE%' 
) 

-- all maximum 
select account_id, count(1) 
from accounts acc 
where exists(
    select 1 
    from accounts_2_user_rights a2ur 
    inner join user_rights ur 
    on ur.rights_id = a2ur.rights_id 
    where a2ur.account_id = acc.account_id 
    and count(1) = 9 
) 
+0

谢谢你的第一个,但所有最大值都不好,它说非法使用了一个聚合函数 – alex1111

+0

好吧,我没有真正测试它,它的一种伪代码。您可以跳过存在,只是在where中使用子查询。类似于(...)where(SELECT COUNT(1)(...))= 9。或使用GROUP BY并使用HAVING关键字。 – GercoOnline

0

我建议你在SQLfiddle上创建一个例子。到现在为止,我只是告诉我该怎么做。如果您提供代码,我会提供代码。

Basicaly你生病做一个子查询通过user_rights加入权限来获取账户ID和饲料查询通过帐户。 这是理想跟踪准代码:

select * from accounts where account_id in (
    select account_id from user_rights_per_account 
    join user_rights on user_right_id = user_right_id 
    where (your filter) 
) 

你可以不这样做的子查询,但这样一来,你就不需要使用不同。 如果你需要做一个聚合,你可以做另一个子查询。