简体   繁体   English

MySQL查询选择/连接concat错误

[英]MySQL query select/join concat error

What is the correct way to perform this query? 执行此查询的正确方法是什么? Additionally, I'd like to trim spaces from fullname, because if middle is empty it still returns the spaces before and after it. 另外,我想从全名中删除空格,因为如果middle为空,它仍会返回其前后的空格。

SELECT first,middle,last, 
CONCAT(first,' ',middle,' ',last) AS fullname
FROM names a 
LEFT JOIN info b ON fullname = b.name
LIMIT 1

the current error is: ERROR 1054 (42S22): Unknown column 'fullname' in 'on clause' 当前错误是: ERROR 1054 (42S22): Unknown column 'fullname' in 'on clause'

The problem that you are facing is that you are trying to join on a calculated column. 您面临的问题是您尝试在计算列上进行联接。

You need to first calculate the column in a subselect, and then join to that 'table' 您需要首先计算子选择中的列,然后加入该“表”

Something like 就像是

SELECT  *
FROM    (
            SELECT  first,
                    middle,
                    last,  
                    CONCAT(first,' ',middle,' ',last) AS fullname 
            FROM    names 
        ) a  LEFT JOIN 
        info b  ON  fullname = b.name 
LIMIT 1 

You can also have a look at the CASE Statement for the spaces in the middle. 您还可以查看中间空格的CASE语句

You can't use an alias in the ON clause. 您不能在ON子句中使用别名。 Try doing 尝试做

SELECT first,middle,last,
CONCAT(first,' ',middle,' ',last) AS fullname
FROM names a 
LEFT JOIN info b ON b.name=CONCAT(first,' ',middle,' ',last) 

"The conditional_expr used with ON is any conditional expression of the form that can be used in a WHERE clause" (from dev.mysql.com/doc/refman/5.1/en/join.html). “与ON一起使用的conditional_expr是可以在WHERE子句中使用的任何形式的条件表达式”(来自dev.mysql.com/doc/refman/5.1/en/join.html)。

So as a logical inference you're not allowed to use aliases in ON clauses. 因此,作为逻辑推断,不允许在ON子句中使用别名。

Try this: 尝试这个:

select first, last, CONCAT(first,' ',middle,' ',last) as fullNAME from names a left join info b on (CONCAT(first,' ',middle,' ',last) =b.name) 从名称(CONCAT(first,'',middle,'',last)= b.name)的左连接信息b的名称中选择first,last,CONCAT(first,'',, middle,'',last)作为fullNAME

one more thing, u have skipped a comma after last in ur select query 还有一件事,在您的选择查询中,您在最后一个之后跳过了逗号

try this , 尝试这个 ,

SELECT CONCAT(first,' ',middle,' ',last) AS fullname FROM names a SELECT CONCAT(first,'',middle,'',last)AS全名FROM命名一个

LEFT JOIN info b 左联接信息b

ON fullname = b.name ON全名= b.name

LIMIT 1 限制1

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

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