有人请帮帮我。
我有2个表,我的数据库是MySQL
表1
user_id | username
------- | --------
1 | joni
2 | adam
3 | jerry
4 | Dino
表2
dokumen_id | create_by | update_by | last_access_by |
doc_001 | 2 | 1 | 2 |
doc_002 | 3 | 2 | 1 |
doc_003 | 1 | 1 | 4 |
我想在一个查询中加入2个表,结果如下
dokumen_id | create_by | update_by | last_access_by |
doc_001 | adam | joni | adam |
doc_002 | jerry | adam | joni |
doc_003 | joni | joni | dino |
我该如何编写查询?
非常感谢你的帮助。答案 0 :(得分:2)
您需要加入table1
三次
SELECT t2.dokumen_id,
c.username AS create_by,
u.username AS update_by,
l.username AS last_access_by
FROM table2 t2
LEFT JOIN table1 c
ON t2.create_by = c.user_id
LEFT JOIN table1 u
ON t2.update_by = u.user_id
LEFT JOIN table1 l
ON t2.last_access_by = l.user_id
左外部联接用于返回table2
中的所有记录,用户可能在create_by
中但不在last_access_by
中,在这种情况下,内部联接将过滤记录不在create_by
答案 1 :(得分:2)
使用table1
table2
三次
select t1.dokumen_id,
tc.username create_by,
tu.username update_by,
ta.username last_access_by
from table2 t1
left outer join table1 tc
on tc.user_id = t1.create_by
left outer join table1 tu
on tu.user_id = t1.update_by
left outer join table1 ta
on ta.user_id = t1.last_access_by;
答案 2 :(得分:0)
SELECT * FROM table1
LEFT JOIN table2
ON table1.user_id=table2.last_access_by;
答案 3 :(得分:0)
你需要加入table1三次
SELECT t2.dokumen_id,
c.username AS create_by,
u.username AS update_by,
l.username AS last_access_by
FROM table2 t2
LEFT JOIN table1 c
ON t2.create_by = c.user_id
LEFT JOIN table1 u
ON t2.update_by = u.user_id
LEFT JOIN table1 l
ON t2.last_access_by = l.user_id