简体   繁体   中英

Join two fields from same table in mysql

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

The problem that is two references of usuario (alias or img_src) per row:

And I get this error:

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

Or this

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

Works, but I get same name and image for each _to and _from

So, what's the way to go here?

Yes joining the same table will require unique alias for the table name something as

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

If you use the same table twice you need different alias names

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM