我有以下结构:
TABLE1 TABLE2
id_worker_main id_worker
id_worker_sub name_worker
我需要选择为id_worker_main和id_worker_sub获取name_worker,但我不能。以下查询返回两次相同的名称。
SELECT t2.name_worker as main, t2.name_worker as sub
FROM table1
INNER JOIN table2 ON t1.id_worker_main = t2.id_worker AND t1.id_worker_sub = t2.id_worker
答案 0 :(得分:2)
您必须两次加入同一张桌子。只需为每个联接使用不同的别名
<强> Sql Fiddle Demo 强>
有了这个工人
INSERT INTO Table2
([id_worker], [name_worker])
VALUES
(1, 'Juan'),
(2, 'Angela'),
(3, 'Peter');
这种关系
INSERT INTO Table1
([id_worker_main], [id_worker_sub])
VALUES
(1, 2),
(2, 3),
(1, 3);
使用此查询
SELECT A.name_worker MAINWORKER, B.name_worker SUBWORKER
FROM Table1 T1
Inner join Table2 A
ON T1.id_worker_main = A.id_worker
Inner join Table2 B
ON T1.id_worker_sub = B.id_worker
<强>输出强>
| MAINWORKER | SUBWORKER |
|------------|-----------|
| Juan | Angela |
| Angela | Peter |
| Juan | Peter |
答案 1 :(得分:1)
如果我正确理解您的问题,您可以多次加入table2
SELECT t21.name_worker as main, t22.name_worker as sub
FROM table1 t1
JOIN table2 t21 on t21.id_worker = t1.id_worker_main
JOIN table2 t22 on t22.id_worker = t1.id_worker_sub