关系之间的内在联系

时间:2012-06-14 13:04:03

标签: c# .net sql join

我想从三个表中获取数据:rolepermissionright。我使用内连接。

代码

SqlConnection con = Class3 .GetConnection();
public DataSet showoption1()
{
    string sql1 = "select  right.rightname,role.rolename
                   FROM permission
                   INNER JOIN ON right.rightid = permission.rightid
                   INNER JOIN role ON permission.roleid = role.roleid  ";
    SqlCommand cmd = new SqlCommand(sql1, con);
    SqlDataAdapter adptr = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    adptr.Fill(ds);
    DataTable table = ds.Tables[0];
    return ds;
}

数据库表

角色

Role Id   Role name
  1       admin
  2       employee

从右

rifgtid    rightname
      1    view courses
      2    view assessmenttest

权限(关联)

permissionid    rightid     roleid
   1             1           2
   2             1           1

2 个答案:

答案 0 :(得分:3)

我不确定你在问什么,但你的sql语法有错误

SELECT      right.rightname,
            role.rolename 
FROM        permission 
INNER JOIN  right ON right.rightid = permission.rightid 
INNER JOIN  role ON permission.roleid = role.roleid

我将INNER JOIN ON替换为INNER JOIN right ON

作为旁注,配置ADO.NET相关对象(SqlConnection,SqlCommand,SqlDataAdapter)

答案 1 :(得分:2)

如果表的名称是RIGHT,那么您需要分隔该名称,因为它是reserved word,例如

SELECT      [right].rightname,
            role.rolename 
FROM        permission 
INNER JOIN  [right] ON [right].rightid = permission.rightid 
INNER JOIN  role ON permission.roleid = role.roleid

(窃取@ Claudio的查询)。但我实际上建议您重新访问架构并为表选择一个不同的非保留名称。