简体   繁体   English

MySQL选择CONCAT条件

[英]MySQL select with CONCAT condition

I'm trying to compile this in my mind.. i have a table with firstname and lastname fields and i have a string like "Bob Jones" or "Bob Michael Jones" and several others. 我想在脑海里编译这个...我有一个带有firstname和lastname字段的表,我有一个像“Bob Jones”或“Bob Michael Jones”这样的字符串和其他几个字符串。

the thing is, i have for example Bob in firstname, and Michael Jones in lastname 问题是,我在名字中有Bob,在姓氏中有Michael Jones

so i'm trying to 所以我想

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

but it says unknown column "firstlast".. can anyone help please ? 但它说未知的专栏“firstlast”..任何人都可以帮忙吗?

The aliases you give are for the output of the query - they are not available within the query itself. 您提供的别名用于查询的输出 - 它们在查询本身中不可用。

You can either repeat the expression: 您可以重复表达式:

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

or wrap the query 或者包装查询

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

Try this: 试试这个:

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

Use CONCAT_WS(). 使用CONCAT_WS()。

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

The first argument is the separator for the rest of the arguments. 第一个参数是其余参数的分隔符。

There is an alternative to repeating the CONCAT expression or using subqueries. 可以使用重复CONCAT表达式或使用子查询的替代方法。 You can make use of the HAVING clause, which recognizes column aliases. 您可以使用HAVING子句来识别列别名。

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

Here is a working SQL Fiddle . 这是一个有效的SQL小提琴

Try: 尝试:

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

Your alias firstlast is not available in the where clause of the query unless you do the query as a sub-select. 除非您将查询作为子选择执行,否则您的别名firstlast在查询的where子句中不可用。

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

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