需要帮助构建SQL查询

时间:2012-11-07 18:17:58

标签: mysql sql

我有三个表如下:

这一张表:m_application_resources

 resourceid resource_name   menu_group_id   menu_name   creation_date   last_created_by updation_date   last_updated_by

和第二个表:m_roles

roleid  rolename    description creation_date   last_created_by updation_date   last_updated_by

,第三个表是:m_access_matrix

accessid    resourceid  roleid  creation_date   last_created_by updation_date   last_updated_by

表的关系是:resourceid和roleid

和我的查询

select  am.accessid, ar.resource_name,rls.rolename
from m_application_resources ar, m_roles rls,m_access_matrix am 
where ar.resourceid=am.resourceid 

返回以下内容:

ccessid resource_name   rolename
1   DepartmentAction    Admin
1   DepartmentAction    Client
1   DepartmentAction    Doctors
2   PositionsAction     Admin
2   PositionsAction     Client
2   PositionsAction     Doctor

结果是错误的,我不知道该如何去做。

Ex:DepartmentAction应该只出现一次,角色名称应该是任何一个。

Sqlfiddle Fiddle

请帮忙

2 个答案:

答案 0 :(得分:3)

role_id上没有条件:

select  am.accessid, ar.resource_name,rls.rolename
from m_application_resources ar, m_roles rls,m_access_matrix am 
where ar.resourceid=am.resourceid AND am.roleid = rls.roleid

为了更清晰,我会将查询转换为连接的ANSI SQL语法:

SELECT am.accessid, ar.resource_name,rls.rolename
FROM m_application_resources ar
JOIN m_access_matrix am ON ar.resourceid=am.resourceid
JOIN m_roles rls ON am.roleid = rls.roleid

答案 1 :(得分:2)

最好在查询中显式连接表。我不是100%肯定我理解你的桌子,但这应该有效:

SELECT am.accessid, ar.resource_name, rls.rolename
FROM (m_application_resources ar INNER JOIN m_access_matrix am 
ON ar.resourceid = am.resourceid) INNER JOIN mroles rls ON am.roleid = rls.roleid