2016-12-26 40 views
-2

有人请帮助我。JOIN 2 SQL表(表1中的1个字段替换另一个表中的1个字段)

我有2个表,我的数据库是MySQL的

table1的

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   | 

how d o我写查询?

非常感谢您的帮助。

+0

你可以帮助自己 “stackoverflow.com通过名称取代IDS加入2 SQL数据库表”。 – philipxy

+0

感谢@philipxy但这个问题不能回答我的问题。我在表2中有多个字段ID。 –

+0

建议您阅读多个结果链接。例如* second *是[Multiple MySQL Table JOINs/id-to-value replacement/aliases](http://stackoverflow.com/questions/11102669/multiple-mysql-table-joins-id-to-value-replacement-别名)。 – philipxy

回答

1

你需要加入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

+0

非常感谢@Prdp。我收到了查询。 :D. –

+0

@Prdp见。告诉你 – GurV

+0

我的意思是我从我的答案@Prdp –

1

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; 
加入 table1三次
+0

dup查询;) –

+0

当你在'select'中有一个'*'时,我已经发布了整个东西:D – GurV

+0

这在中间没什么大不了的编辑 –

0
SELECT * FROM table1 
LEFT JOIN table2 
ON table1.user_id=table2.last_access_by; 
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 
相关问题