简体   繁体   English

SELECT AS别名上的LEFT JOIN导致在WHERE语句上找不到列

[英]LEFT JOIN on SELECT AS alias causing column not found on WHERE statement

I want to search user by 'user_location' which is an alias of location.detail And I made this following query : 我想通过“ user_location”来搜索用户,“ user_location”是location.detail的别名,然后执行以下查询:

SELECT user.*, location.detail as user_location 
FROM user 
LEFT JOIN location
ON user.id = location.user_id
WHERE user_location = 'jakarta';

It's resulting error says, 结果错误说,

Column not found: 1054 Unknown column 'user_location' in 'where clause' 

Why is it? 为什么? what is the solution? 解决办法是什么? Any answer will be highly appreciated! 任何答案将不胜感激!

You can't user an alias in the where in the same query you created it. 您不能在创建别名的同一查询中的where中使用别名。 So you should do: 因此,您应该执行以下操作:

SELECT user.*, location.detail as user_location 
  FROM user 
        LEFT JOIN location
          ON user.id = location.user_id
 WHERE location.detail = 'jakarta';

If you still want to use that column you have to wrap it in a subquery: 如果仍要使用该列,则必须将其包装在子查询中:

select * from
(
SELECT user.*, location.detail as user_location 
  FROM user 
        LEFT JOIN location
          ON user.id = location.user_id
) a
where user_location = 'jakarta';

As @spencer7593 mentioned you can use an alias in the same query in the HAVING clause. 如@ spencer7593所述,您可以在HAVING子句的同一查询中使用别名。

The obvious and correct solution is to repeat the expression in the WHERE clause. 显而易见且正确的解决方案是在WHERE子句中重复该表达式。 Sometimes, the expressions are more complicated (think distance calculations). 有时,表达式更复杂(请考虑距离计算)。 MySQL has an extension to SQL that allows you to use HAVING for this purpose: MySQL对SQL进行了扩展,允许您为此使用HAVING

SELECT u.*, l.detail as user_location 
FROM user u LEFT JOIN
     location l
     ON u.id = l.user_id
HAVING user_location = 'jakarta';

I don't actually recommend it for this particular query (after all, "user_location" is longer to type out than "l.detail"). 对于这个特定的查询,我实际上并不建议这样做(毕竟,“ user_location”要比“ l.detail”更长)。 Under some circumstances, though, this can be convenient. 但是,在某些情况下,这可能很方便。

More important than these considerations is that your query is really an INNER JOIN . 比这些考虑因素更重要的是,您的查询实际上是INNER JOIN You should specify it as such: 您应该这样指定:

SELECT u.*, l.detail as user_location 
FROM user u INNER JOIN
     location l
     ON u.id = l.user_id
WHERE l.detail = 'jakarta';

The filtering condition filters out all unmatched rows. 过滤条件会过滤掉所有不匹配的行。 Using a LEFT JOIN inappropriately confuses people and might confuse the optimizer. 使用LEFT JOIN不恰当地使人们感到困惑,并可能使优化器感到困惑。

You cannot use aliases in Where clause in mysql. 您不能在mysql的Where子句中使用别名。 Try 尝试

SELECT user.*, location.detail as user_location 
FROM user 
LEFT JOIN location
ON user.id = location.user_id
WHERE location.detail = 'jakarta';

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

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