简体   繁体   中英

MySQL: How to use column alias in left join?

I am trying to use column alias in the left join but I get sql error with uknown field.

select *, (select SenderId from messages where messageId = 5) as senderId  from threads 
Left join users where users.id = senderId

This query is quite simple but why is not it working or what is the best way to achieve this ?

I'll really appreciate any contribution. Thanks

You can't use column aliases in ON or WHERE clauses, because column aliases are assigned to values in the result set, but ON and WHERE are used to create the result set. You need to use another JOIN .

SELECT t.*, m.senderId, u.*
FROM threads AS t
CROSS JOIN messages AS m
LEFT JOIN users AS u ON u.id = m.SenderId
WHERE m.messageId = 5
select t.*, mu.* 
 from threads as t
 Left Join
           (select SenderId,users. *  
            from messages, users  
            where messages.messageId 
            =  users.id and messsageId = 5) as mu

You need to join threads and mu tables with some id

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