MYSQL多次连接表

时间:2011-06-10 03:27:17

标签: mysql sql join foreign-keys referential-integrity

我有一个包含各种事件的表格,每个都有(在很多其他字段中)addedbyusereditedbyuserdeletedbyuserINT,并向特定用户返回users表。 我可以加入其中一个字段(比如addedbyuser)而没有任何问题,我如何加入其余的并在php中引用它们?

事件表:

eventid addedbyuser editedbyuser deletedbyuser
1       1           2            3

用户表:

id username
1  name1
2  name2
3  name3

基本上,我想显示添加,编辑和删除文章的人的姓名,我可以在一个SQL查询中执行此操作吗?

1 个答案:

答案 0 :(得分:16)

这样的事情:

select 
    evn.eventid, 
    us1.username as addedbyuser, 
    us2.username as editedbyuser, 
    us3.username as deletedbyuser, 
from events evn
    join users as us1 on
        evn.addedbyuser = us1.id
    join users as us2 on
        evn.editedbyuser = us2.id
    join users as us3 on
        evn.deletedbyuser = us3.id