需要查询才能从多个表中检索记录

时间:2013-12-12 20:31:16

标签: sql database

表格结构:

role_assignment
 id | contextid | userid    
----+-----------+--------
  1 |        17 |      3    
  2 |        23 |      3
上下文
 id | instanceid
----+------------
 17 |          2
 23 |          3
当然
 id | name
----+----------
  2 | course 1
  3 | course 2

我需要检索所有课程名称,例如userid = 3(或任何其他)

修改

我认为这有效:

SELECT course.shortname FROM role_assignments, context, course
WHERE userid = 3
  AND role_assignments.contextid = context.id
  AND context.instanceid = course.id;

但任何人都可以使用连接改进吗?

2 个答案:

答案 0 :(得分:0)

SELECT course.shortname 
FROM role_assignments INNER JOIN context
ON role_assignments.contextid = context.id
INNER JOIN course
ON context.instanceid = course.id
WHERE userid = 3

答案 1 :(得分:0)

假设上下文的instanceid匹配" id"列当然,以下查询将返回您想要的内容:

select name from course where id in (select c.instanceid from context c, role_assignment b where c.id=b.contextid and b.userid=3);

+----------+
| name     |
+----------+
| course 1 |
| course 2 |
+----------+

使用联接查询将是:

select distinct name from role_assignment join context on role_assignment.contextid = context.id  join course on context.instanceid = course.id where userid=3;

请注意,您需要使用distinct来返回唯一结果。