MySQL select with CONCAT condition

*爱你&永不变心* 提交于 2019-11-26 04:42:45

问题


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.

the thing is, i have for example Bob in firstname, and Michael Jones in lastname

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 ?


回答1:


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"



回答2:


Try this:

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



回答3:


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



回答4:


Use 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.




回答5:


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.




回答6:


There is an alternative to repeating the CONCAT expression or using subqueries. You can make use of the HAVING clause, which recognizes column aliases.

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

Here is a working SQL Fiddle.



来源:https://stackoverflow.com/questions/5734570/mysql-select-with-concat-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!