MySQL 使用 LIKE 查询 SELECT 行并创建包含匹配字符串的新列

MySQL query to SELECT rows with LIKE and create new column containing the matched string

我需要一些关于 MySQL 查询的帮助,我现在已经苦苦挣扎了一段时间。

因此,我正在尝试创建一个 MySQL 查询,以从 table 匹配特定字符串(如 app)的 SELECT 行。 我的table是这样的:

+-----+--------------+
| id  | name         |
+-----+--------------+
|   1 | Green Apple  |
|   2 | Big Orange   |
|   3 | application  |
+-----+--------------+

我可以找到包含 app 字符串且 SELECTLIKE 的所有行。

但是,我还想创建新列,其中包含 name 列中与 app 匹配的字符串,并保持数据库区分大小写的格式,即与 app 匹配根据 name.

中的字符串格式,新列将包含 Appapp 个词组

到目前为止我的查询是这样的:

SELECT *, 'what_to_put?' as new_column FROM table WHERE name LIKE '%".$app."%'

所需的输出如下:

+-----+--------------+-------------+
| id  | name         | new_column  |
+-----+--------------+-------------+
|   1 | Green Apple  |     App     |
|   2 | application  |     app     |
+-----+--------------+-------------+

知道如何实现吗?

如果没有单独的正则表达式库,您将需要使用内置的 string functions to find the location of the match, and then extract the matching sub-string:

SELECT 
  id, 
  name, 
  substring(name, locate('app', name), length('app')) as new_column 
FROM yourTable 
WHERE name LIKE '%app%'

给出结果:

+----+-------------+------------+
| id |    name     | new_column |
+----+-------------+------------+
|  1 | Green Apple | App        |
|  3 | application | app        |
+----+-------------+------------+

Sql Fiddle Here