117

我试图在我的脑海中编译这个..我有一个包含名字和姓氏字段的表,我有一个像“Bob Jones”或“Bob Michael Jones”这样的字符串等等。

问题是,例如,我的名字中有 Bob,姓氏中有 Michael Jones

所以我想

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

但它说未知列“firstlast”..有人可以帮忙吗?

4

6 回答 6

180

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

您可以重复表达式:

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"
于 2011-04-20T18:02:08.780 回答
34

尝试这个:

SELECT * 
  FROM  (
        SELECT neededfield, CONCAT(firstname, ' ', lastname) as firstlast 
        FROM users 
    ) a
WHERE firstlast = "Bob Michael Jones"
于 2011-04-20T18:00:17.827 回答
10
SELECT needefield, CONCAT(firstname, ' ',lastname) as firstlast 
FROM users 
WHERE CONCAT(firstname, ' ', lastname) = "Bob Michael Jones"
于 2011-04-20T17:59:55.860 回答
8

使用 CONCAT_WS()。

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

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

于 2014-01-20T10:37:55.193 回答
7

尝试:

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

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

于 2011-04-20T18:00:15.423 回答
7

除了重复CONCAT表达式或使用子查询之外,还有另一种方法。您可以使用HAVING识别列别名的子句。

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

这是一个有效的SQL Fiddle

于 2014-01-10T14:32:37.353 回答