JOIN查询,ON相同的键

时间:2011-08-21 17:20:27

标签: sql select join

我有一些桌子。此JOIN查询中最重要的是:

table 'changes' columns:
|----|------------|----------|------------|-----|----------------|
| id | teacher_id | class_id | subject_id | day | new_teacher_id |
|----|------------|----------|------------|-----|----------------|
|----|--sample input:--------|------------|-----|----------------|
|---1|-----------1|---------1|-----------1|2002-02-02|----------2|

table 'teachers' columns:
|----|---------|
| id | teacher |
|----|---------|
|sample input:-|
|---1|mr. Johnson|
|---2|mr. John-|
|--------------|

以下查询正常:

SELECT c.day, t.teacher, cl.class, s.subjectname
FROM changes AS c
LEFT JOIN teachers AS t ON c.teacher_id = t.id
JOIN classes AS cl ON c.class_id = cl.id
JOIN subjects AS s ON c.subject_id = s.id

但我也希望做出类似的事情:

LEFT JOIN teachers AS t ON c.teacher_id = t.id AND c.new_teacher_id = t.id

工作。

任何想法如何从同一个表中加入两个列,而另一个键列来自另一个?

2 个答案:

答案 0 :(得分:3)

您可以通过为表添加单独的别名来多次加入表:

SELECT t2a.name AS one_name, t2b.name AS two_name, ...
FROM table1 AS t1 JOIN table2 AS t2a (ON t2a.id = t1.one_id)
                  JOIN table2 AS t2b (ON t2b.id = t1.two_id)

答案 1 :(得分:1)

将它放在你的WHERE子句中:

SELECT c.day, t.teacher, cl.class, s.subjectname
FROM changes AS c
LEFT JOIN teachers AS t ON c.teacher_id = t.id
JOIN classes AS cl ON c.class_id = cl.id
JOIN subjects AS s ON c.subject_id = s.id
WHERE c.new_teacher_id = t.id