问题
I need a SQL query to get the common words only between two sentences. For example:
Sentence 1: This site is very helpful
Sentence 2: I need a helpful site
The result should be: site helpful
Also, if I need to compare sentence 1 to table field records to get the record that contains most common words to sentence 1, what can I do?
回答1:
You question title says MSQL, so I'm taking your question as a Sql Server question.
- Split function
Depending on SQL Server version/Server Configuration, you'll need a split function that can split a string on a delimiter of choice. Here's such a function.
CREATE FUNCTION [dbo].[fnSplit](@data NVARCHAR(MAX), @delimiter NVARCHAR(5))
RETURNS @t TABLE (rowNum int IDENTITY(1,1), data NVARCHAR(max), descriptor varchar(255) NULL)
AS
BEGIN
DECLARE @textXML XML;
SELECT @textXML = CAST('<d>' + REPLACE(@data, @delimiter, '</d><d>') + '</d>' AS XML);
INSERT INTO @t(data)
SELECT RTRIM(LTRIM(T.split.value('.', 'nvarchar(max)'))) AS data
FROM @textXML.nodes('/d') T(split)
RETURN
END
- Query for common words using split function (there are quite a few ways to do this, here's one).
SELECT sentence1.data FROM dbo.fnSplit('This site is very helpful',' ') sentence1 INNER JOIN dbo.fnSplit('I need a helpful site',' ') sentence2 ON sentence1.data = sentence2.data
来源:https://stackoverflow.com/questions/13864446/query-to-get-common-words-between-two-strings