php MySQL查询从字段中提取第一个单词
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/689858/
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
MySQL query to extract first word from a field
提问by Stuart
I would like to run a query that returns the first word only from a particular field, this field has multiple words separated by spaces, I assume I may need to carry out some regex work to accomplish this? I know how to do this using a few ways in PHP but this would best be carried out on the database side. Any ideas much appreciated. Thanks.
我想运行一个查询,只从特定字段返回第一个单词,这个字段有多个用空格分隔的单词,我假设我可能需要执行一些正则表达式工作来完成这个?我知道如何使用 PHP 中的几种方法来做到这一点,但这最好在数据库端进行。任何想法都非常感谢。谢谢。
回答by evilpenguin
SUBSTRING_INDEX: http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index
SUBSTRING_INDEX:http: //dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_substring-index
SELECT SUBSTRING_INDEX(`name`, ' ', 1);
回答by Bogdan Constantinescu
Here you go :)
干得好 :)
SELECT SUBSTRING_INDEX( `field` , ' ', 1 ) AS `field_first_word`
FROM `your_table`
回答by Manrico Corazzi
select
substring(test_field, 1, instr(test_field, ' '))
from
test_table
回答by Seb
SELECT
SUBSTR(field_name, 1, LOCATE(' ', field_name)) AS first_word
FROM
table

