MySQL选择CONCAT条件

时间:2011-04-20 17:57:45

标签: mysql select conditional-statements where concat

我正在尝试在脑海中编译这个...我有一个带有firstname和lastname字段的表 我有一个像“Bob Jones”或“Bob Michael Jones”等字符串。

事情是,我有例如 鲍勃在名字,和 迈克尔琼斯的姓氏

所以我想

SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
  FROM users 
 WHERE firstlast = "Bob Michael Jones"

但它说未知专栏“firstlast”..任何人都可以帮忙吗?

6 个答案:

答案 0 :(得分:168)

您提供的别名用于查询的输出 - 它们在查询本身中不可用。

您可以重复表达式:

SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
FROM users
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"

或包装查询

SELECT * FROM (
  SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
  FROM users) base 
WHERE firstLast = "Bob Michael Jones"

答案 1 :(得分:34)

试试这个:

SELECT * 
  FROM  (
        SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
        FROM users 
    ) a
WHERE firstlast = "Bob Michael Jones"

答案 2 :(得分:10)

SELECT needefield, CONCAT(firstname, ' ',lastname) as firstlast 
FROM users 
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"

答案 3 :(得分:8)

使用CONCAT_WS()。

SELECT CONCAT_WS(' ',firstname,lastname) as firstlast FROM users 
WHERE firstlast = "Bob Michael Jones";

第一个参数是其余参数的分隔符。

答案 4 :(得分:7)

尝试:

SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
  FROM users 
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"

除非您将查询作为子选择执行,否则您的别名firstlast在查询的where子句中不可用。

答案 5 :(得分:7)

可以选择重复CONCAT表达式或使用子查询。您可以使用HAVING子句来识别列别名。

SELECT 
  neededfield, CONCAT(firstname, ' ', lastname) AS firstlast 
FROM
  users 
HAVING firstlast = "Bob Michael Jones"

这是一个有效的SQL Fiddle