0

假设我们有下表。

用户名 | 信息
--------|-------------
1 | 嗨,祝你有美好的一天
2 | 嗨,我度过了愉快的一天

我需要分别拥有所有 { Hi,-have-a-nice-day-I-had } 单词。有什么办法吗?如果我想从整个数据库表中导出单词怎么办?

类似的结果也会很好。

4

2 回答 2

2

好吧,好吧,就这样吧。

在 SQL Server 中,您可以使用此...

SELECT word = d.value('.', 'nvarchar(max)')
FROM
    (SELECT xmlWords = CAST(
        '<a><i>' + replace([Message], ' ', '</i><i>') + '</i></a>' AS xml) 
        FROM MyMessageTbl) T(c)
    CROSS APPLY c.nodes('/a/i') U(d)

我希望对于 MySQL,您可以使用相同的东西,使用 XML 支持 - ExtractValue() 等。

编辑:解释

 - replace([Message], ' ', '</i><i>') replaces e.g. 'my word' with 'my</i><i>word'
 - then I add the beginning and the end of xml -> '<a><i>my</i><i>word</i></a>', so I have a valid xml... and cast it to xml type to be able to do something with it
 - I select from that xml and shred xml nodes '/a/i' it to rows using CROSS APPLY c.nodes('/a/i'); 
   alias rows using U(d), so one 'i' maps to column d (e.g. 'my')
 - d.value('.', 'nvarchar(max)') extracts node content and casts it to character type
于 2012-10-29T08:38:35.867 回答
2

试试这个:在 Sql server 2005 或更高版本中

create table yourtable(RowID int, Layout varchar(200))
INSERT yourtable VALUES (1,'hello,world,welcome,to,tsql')
INSERT yourtable VALUES (2,'welcome,to,stackoverflow')


;WITH SplitSting AS
(
    SELECT
        RowID,LEFT(Layout,CHARINDEX(',',Layout)-1) AS Part
            ,RIGHT(Layout,LEN(Layout)-CHARINDEX(',',Layout)) AS Remainder
        FROM YourTable
        WHERE Layout IS NOT NULL AND CHARINDEX(',',Layout)>0
    UNION ALL
    SELECT
        RowID,LEFT(Remainder,CHARINDEX(',',Remainder)-1)
            ,RIGHT(Remainder,LEN(Remainder)-CHARINDEX(',',Remainder))
        FROM SplitSting
        WHERE Remainder IS NOT NULL AND CHARINDEX(',',Remainder)>0
    UNION ALL
    SELECT
        RowID,Remainder,null
        FROM SplitSting
        WHERE Remainder IS NOT NULL AND CHARINDEX(',',Remainder)=0
)
SELECT part FROM SplitSting ORDER BY RowID

SQLFIDDLE 演示

于 2012-10-29T08:33:39.540 回答