簡體   English   中英

Mysql:使用regexp匹配作為字段?

[英]Mysql: using regexp matches as fields?

我閱讀了關於regexpmysql文檔,但看起來regexp 只能用作WHERE過濾器來匹配SELECT查詢中的行。

我想知道是否可以將正則表達式的匹配作為列提取,例如,如果在我的表中我有一個SKU文本字段:

+----------------+--------------+---------------+
|sku             | product_name | [other fields]|
+----------------+--------------+---------------+
|ART-2830--107-70| Foo          |               |
|ART-2832--115-6 | Bar          |               |
+----------------+--------------+---------------+

發出一個匹配正則表達式(ART-)([0-9]+)(--)([0-9]+)(-)([0-9]+)的選擇查詢會很棒我作為輸出:

+------+------------+-------+----------+
| type | collection | model | material |
+------+------------+-------+----------+
| ART  | 2830       | 107   | 70       |
| ART  | 2832       | 115   | 6        |
+------+------------+-------+----------+

請注意,我的表中不存在type, collection, model and material列,僅僅是上面正則表達式的匹配項。

這可能嗎?

ps:我知道將這個表標准化為我需要的每個屬性添加一個列是一個很好的想法,但這是我必須使用的結構,我現在無法編輯它。

編輯以防有人需要這個,我看到PostgreSql提供此功能

答案通常是“不” - 至少在沒有大量強力編碼的情況下也是如此。 但是,你很幸運,因為你可以在MySQL中“輕松”地做你想做的事情:

select substring_index(sku, '-', 1) as type,
       reverse(substring_index(reverse(substring_index(sku, '-', 2)), '-', 1)) as collection,
       reverse(substring_index(reverse(substring_index(sku, '-', 4)), '-', 1)) as model,
       reverse(substring_index(reverse(substring_index(sku, '-', 5)), '-', 1)) as material
from skus

好吧,也許不是最明顯的功能集合。 但這是它對模型的作用:

開始於: ART-2830--107-70

substring_index(sku, '-', 4) --> ART-2830--107

reverse()

701--0381-TRA

substring_index( . . . 1)

701

最后的reverse()

107

在select語句中使用regex實際上取決於sql語言。 對於MySql,您可以在手冊中閱讀更多內容。

本手冊的這一部分討論了如何使用正則表達式選擇語句: http//dev.mysql.com/doc/refman/5.7/en/regexp.html 該手冊頁還具有以下鏈接,以指示如何對where語句使用正則表達式語句的示例。

http://dev.mysql.com/doc/refman/5.7/en/pattern-matching.html

此示例也在手冊中。

To find names containing a “w”, use this query:

mysql> SELECT * FROM pet WHERE name REGEXP 'w';
+----------+-------+---------+------+------------+------------+
| name     | owner | species | sex  | birth      | death      |
+----------+-------+---------+------+------------+------------+
| Claws    | Gwen  | cat     | m    | 1994-03-17 | NULL       |
| Bowser   | Diane | dog     | m    | 1989-08-31 | 1995-07-29 |
| Whistler | Gwen  | bird    | NULL | 1997-12-09 | NULL       |
+----------+-------+---------+------+------------+------------+

你可以根據正則表達式捕獲組返回數據嗎?

否.where語句過濾SQL引擎返回的數據。 您需要為要返回的每列數據構建一個條目。 正如在Gordon Linoff的回答中,每列都可以由SQL處理,以手動從給定列中提取數據。 但是這個解決方案遠非使用正則表達式來描述sql select語句的美好理想。

我打算使用正則表達式捕獲組來提取數據,然后在收到數據后需要這樣做。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM