繁体   English   中英

MySQL查询中的Concat()

[英]Concat() in mysql query

我在连接MySQL查询中的字符串时遇到问题。

这是我的查询:

SELECT *, CONCAT(nombre,' ',apellido) AS fullname FROM user WHERE nombre LIKE '%$busqueda%' OR apellido LIKE '%$busqueda%' OR email LIKE '%$busqueda%' OR about LIKE '%$busqueda%' OR place LIKE '%$busqueda%' or fullname LIKE '%$busqueda%'

但是查询失败: Query failed: Unknown column 'fullname' in 'where clause'

可能只是一个sintax错误,thx

您不能在WHERE子句中引用别名。

可以使用AS alias_name为select_expr赋予别名。 别名用作表达式的列名,并且可以在GROUP BY,ORDER BY或HAVING子句中使用。

不允许在WHERE子句中引用列别名,因为执行WHERE子句时可能尚未确定列值。 请参见第C.5.5.4节“列别名的问题”。

资源

你可以改变:

... OR fullname LIKE '%$busqueda%'

... or CONCAT(nombre,' ',apellido) LIKE '%$busqueda%'

顺便说一下,所有这些LIKE都会使您的查询非常缓慢。 您可能想研究全文搜索

串联您自己的字符串,一个参数是字符串,第二个参数是您要使用此CONCAT函数代码进行串联的列名

SELECT concat('ConcatString', columnName )AS newColumnName从products 1限制0,30

您不能对在SELECT语句中创建的字段进行比较。

采用

or CONCAT(nombre,' ',apellido) LIKE %$busqueda%'

请注意,尽管这可能无法针对引擎进行优化,所以搜索可能会非常缓慢。 如果这是用于大量数据,我将考虑保留单独的串联列以供搜索。

您还需要将Concat()放在WHERE中:

...place LIKE '%$busqueda%' OR CONCAT(nombre,' ',apellido) LIKE '%$busqueda%'

采用 :

SELECT *, CONCAT(nombre,' ',apellido) AS fullname FROM user WHERE nombre LIKE '%$busqueda%' OR apellido LIKE '%$busqueda%' OR email LIKE '%$busqueda%' OR about LIKE '%$busqueda%' OR place LIKE '%$busqueda%' or CONCAT(nombre,' ',apellido) LIKE '%$busqueda%'

如前所述,您不能在WHERE子句中使用列别名。 这是因为WHERE子句在找到任何值之前WHERE使用,因此直到检索到行之后才计算列别名中的表达式。

现在,如果您不想执行两次CONCAT(一次在SELECT ,一次在WHERE ),则可以利用HAVING子句。 HAVING子句的工作方式与WHERE一样,仅检索行之后使用它。

阅读更多: http : //dev.mysql.com/doc/refman/5.0/en/problems-with-alias.html

SELECT *, CONCAT(nombre,' ',apellido) AS fullname FROM user WHERE nombre LIKE '%$busqueda%' OR apellido LIKE '%$busqueda%' OR email LIKE '%$busqueda%' OR about LIKE '%$busqueda%' OR place LIKE '%$busqueda%' HAVING fullname LIKE '%$busqueda%'

请注意,如果您正在寻找最佳性能 ,则此方法不一定会很好地工作。

罪孽正在杀死我...

下一个查询也有问题:

$cadbusca="SELECT * , MATCH (nombre, apellido, email, about, place, CONCAT(nombre,' ',apellido)) AGAINST ('$busqueda') AS Score FROM user WHERE MATCH (nombre, apellido, email, about, place, CONCAT(nombre,' ',apellido)) AGAINST ('$busqueda') ORDER BY Score DESC";

错误:

Query failed: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '(nombre,' ',apellido)) AGAINST ('dan stern') AS Score FROM user WHERE MATCH (nom' at line 1

暂无
暂无

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

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