MySQL 如何将两列选为一列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7256096/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 20:58:09  来源:igfitidea点击:

How to select two columns as one?

mysql

提问by Bobby

I'm trying to search two fields as one from a MySQL database using PHP.

我正在尝试使用 PHP 从 MySQL 数据库中搜索两个字段作为一个字段。

e.g.

例如

mysql_query("
  SELECT (first_name,last_name) As name
  FROM people
  WHERE (name LIKE '%" . $term . "%')
");

I thought that this was the code to use, but to no avail. It has been a while since I've done this and I can't remember exactly how to achieve the desired result.

我以为这是要使用的代码,但无济于事。我已经有一段时间没有这样做了,我不记得确切地如何达到预期的结果。

回答by dee-see

You're looking for the CONCATfunction.

您正在寻找该CONCAT功能。

mysql_query("SELECT CONCAT(first_name, last_name) As name FROM people WHERE (CONCAT(first_name, last_name) LIKE '%" . $term . "%')");

or even...

甚至...

mysql_query("SELECT CONCAT(first_name, ' ', last_name) As name FROM people WHERE (CONCAT(first_name, ' ', last_name) LIKE '%" . $term . "%')");

I couldn't explain you the reasons behind this (...but maybe someone can leave a comment?), but you can't use the namealias to search for both fields, you have to explicitly CONCATagain.

我无法向您解释这背后的原因(...但也许有人可以发表评论?),但是您不能使用name别名来搜索这两个字段,您必须CONCAT再次明确。

回答by Sam Roberts