2

我在 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错误,谢谢

4

7 回答 7

5

您不能在 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 都会使您的查询变得非常慢。您可能希望改为查看全文搜索

于 2010-12-21T21:06:03.063 回答
0

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

采用

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

请注意,这可能无法针对引擎进行优化,因此搜索可能会非常慢。如果这是针对大量数据的,我会考虑保留一个单独的连接列来进行搜索。

于 2010-12-21T21:06:36.123 回答
0

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

...place LIKE '%$busqueda%' OR CONCAT(nombre,' ',apellido) LIKE '%$busqueda%'
于 2010-12-21T21:06:44.627 回答
0

采用 :

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%'
于 2010-12-21T21:06:53.853 回答
0

如前所述,您不能在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%'

请注意,如果您正在寻找最佳性能,这可能不一定能奏效。

于 2010-12-21T21:10:31.773 回答
0

sintax 正在杀死我....

下一个查询也有问题:

$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
于 2010-12-21T21:26:27.393 回答
0

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

SELECT concat('ConcatString', columnName) AS newColumnName FROM productsWHERE 1 LIMIT 0 , 30

于 2014-02-07T06:36:24.883 回答