简体   繁体   English

MySQL:如何在左联接中使用列别名?

[英]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. 我正在尝试在左联接中使用列别名,但出现未知字段时出现SQL错误。

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. 您不能在ONWHERE子句中使用列别名,因为列别名已分配给结果集中的值,但是ONWHERE用于创建结果集。 You need to use another JOIN . 您需要使用另一个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 您需要使用一些ID连接线程和mu表

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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