CREATE TABLE /插入數據
CREATE TABLE Table1
(`id` INT, `caption` VARCHAR(255), `user` INT)
;
INSERT INTO Table1
(`id`, `caption`, `user`)
VALUES
(1, '#hi i''m here', 2),
(2, 'hello #hi there', 3),
(3, 'i''m x #hi', 4),
(4, 'I''m #Driving', 2),
(5, 'I #love #food', 6)
;
您可以在標題與SUBSTRING_INDEX(SUBSTRING_INDEX(caption, ' ', 1), ' ', -1)
分裂的話拿到的第一個字SUBSTRING_INDEX(SUBSTRING_INDEX(caption, ' ', 2), ' ', -1)
獲得的第二個字。
但是,如何使它動態,讓更多的單詞可以分裂。
首先你用SQL創建一個數字生成器。 這個查詢從1到100
查詢生成號碼列表
SELECT
@number := @number + 1 AS number
FROM (
(SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) row1
CROSS JOIN
(SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) row2
CROSS JOIN
(SELECT @number:=0) AS init_user_params
)
結果
number
--------
1
2
3
4
5
6
7
8
9
10
...
...
90
91
92
93
94
95
96
97
98
99
100
現在我們可以CROSS JOIN與我們的表1我們數生成的列表(在我們的例子中) 這將生成(表計數)* 100個記錄與重複的記錄。 使用所產生的號碼列表在SUBSTRING_INDEX(SUBSTRING_INDEX(caption, ' ', [word offset]), ' ', -1)
像這樣
查詢
SELECT
DISTINCT #remove duplicates
SUBSTRING_INDEX(SUBSTRING_INDEX(caption, ' ', numbers.number), ' ', -1) AS tag
FROM (
SELECT
@number := @number + 1 AS number
FROM (
(SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) row1
CROSS JOIN
(SELECT 0 UNION ALL SELECT 1 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) row2
CROSS JOIN
(SELECT @number:=0) AS init_user_params
)
)
AS numbers
CROSS JOIN Table1
WHERE
SUBSTRING_INDEX(SUBSTRING_INDEX(caption, ' ', numbers.number), ' ', -1) LIKE '#%' #we only want words starting with #
ORDER BY
Table1.id ASC
結果
tag
----------
#hi
#Driving
#love
#food
注意
- 此查詢僅在標題等於100個字或更少時纔有效
- 此查詢在小型表上相當快。在較大的桌子上,這將不能很好地擴展,因爲關閉了加號
- 你真的應該有一個存儲hashtags的表格。
不要以爲你可以做攻略,看https://stackoverflow.com/questions/6617996/simulating-regex-capture-groups-in-mysql –
好像你應該有另一個表中存儲後的井號標籤。 – jarlh
@jarlh喜歡多對多的關係嗎? –