在mysql中加入同一个表中的两个字段

时间:2015-10-25 09:50:13

标签: mysql left-join multiple-columns

SELECT  pms.id, 
                    pms.id_from, 
                    pms.id_to, 
                    pms.fecha, 
                    pms.leida, 
                    usuarios.img_src  as avatar_from, 
                    usuarios.alias as name_from,
                    usuarios.img_src  as avatar_to, 
                    usuarios.alias as name_to  
FROM pms 
LEFT JOIN usuarios ON usuarios.id = pms.id_from
LEFT JOIN usuarios ON usuarios.id = pms.id_to

问题是每行usuario(alias或img_src)的两个引用:

我收到了这个错误:

The following errors were reported:
Not unique table/alias: 'usuarios'

或者这个

SELECT  pms.id, 
                pms.id_from, 
                pms.id_to, 
                pms.fecha, 
                pms.leida, 
                usuarios.img_src  as avatar_from, 
                usuarios.alias as name_from,
                usuarios.img_src  as avatar_to, 
                usuarios.alias as name_to  
FROM pms 
LEFT JOIN usuarios ON usuarios.id = pms.id_from OR usuarios.id = pms.id_to

可以使用,但我为每个_to和_from

获取相同的名称和图像

那么,去这里的方式是什么?

2 个答案:

答案 0 :(得分:3)

是加入同一个表将需要表名的唯一别名

select 
p.id,
p.id_from, 
p.id_to, 
p.fecha, 
p.leida, 
u1.img_src  as avatar_from, 
u1.alias as name_from,
u2.img_src  as avatar_to, 
u2.alias as name_to  
from pms p
LEFT JOIN usuarios u1 ON u1.id = p.id_from
LEFT JOIN usuarios u2 ON u2.id = p.id_to

答案 1 :(得分:3)

如果您使用同一个表两次,则需要不同的别名

SELECT  pms.id, 
        pms.id_from, 
        pms.id_to, 
        pms.fecha, 
        pms.leida, 
        u_from.img_src  as avatar_from, 
        u_from.alias as name_from,
        u_to.img_src  as avatar_to, 
        u_to.alias as name_to 
FROM pms 
LEFT JOIN usuarios u_from ON u_from.id = pms.id_from
LEFT JOIN usuarios u_to ON u_to.id = pms.id_to