我得到一个随机单词列表,我需要与描述或其他文本字段中的任何单词匹配,这些单词不必是连续的。这应该给我任何比赛。如果您考虑它,就像任何单词匹配搜索功能一样。
我回来的字符串,我分成一个空白区域,这会产生一个包含每行不同单词的表格。
如何重用该表来查找任何单词的匹配项,因为我不能使用WHERE IN子句。
DECLARE @split TABLE(word NVARCHAR(2000))
SELECT *
FROM StockSummary
WHERE Reference in (select word from @split)
OR Name in (select word from @split)
OR AlternativeReference in (select word from @split)
OR InternalReference in (select word from @split)
答案 0 :(得分:2)
效率不是很高,但我认为这就是你要找的东西。使用全文索引编写更好的方法。
DECLARE @split TABLE(word NVARCHAR(2000));
SELECT DISTINCT ss.*
FROM StockSummary ss
INNER JOIN @split s
ON ss.Reference LIKE '%' + s.word + '%'
OR ss.Name LIKE '%' + s.word + '%'
OR ss.AlternativeReference LIKE '%' + s.word + '%'
OR ss.InternalReference LIKE '%' + s.word + '%';
请注意,这基本上是执行中的交叉连接。
查找包含所有字词的行:
DECLARE @split TABLE(word NVARCHAR(2000));
SELECT Reference, Name, AlternativeReference, InternalReference
FROM (
SELECT DISTINCT ss.Reference, ss.Name, ss.AlternativeReference, ss.InternalReference, s.word
FROM StockSummary ss
INNER JOIN @split s
ON ss.Reference LIKE '%' + s.word + '%'
OR ss.Name LIKE '%' + s.word + '%'
OR ss.AlternativeReference LIKE '%' + s.word + '%'
OR ss.InternalReference LIKE '%' + s.word + '%';
)
GROUP BY Reference, Name, AlternativeReference, InternalReference
HAVING COUNT(*) = (SELECT COUNT(*) FROM @split);
如果你的列表中有相同的单词两次,DISTINCT将处理重复项,结果中不需要两次(你需要用CHARINDEX做更多的事情)。
答案 1 :(得分:0)
DECLARE @Test TABLE (TestId INT IDENTITY, Test VARCHAR(8), Test2 VARCHAR(8), Test3 VARCHAR(8));
INSERT INTO @Test (Test, Test2, Test3) VALUES ('Duck', NULL, NUll), (NULL, NULL, 'Duck'), ('Sit', NULL, NULL), ('Kneel', NULL, NULL), (NULL, 'Hey', NULL);
--Data as is
Select *
From @Test
--Insert in some hunting data into a table
DECLARE @Find TABLE (word VARCHAR(8));
INSERT INTO @Find (word) VALUES ('Duck'),('Sit');
--match cte on multiple join conditions
; With x as
(
SELECT
a.*
, CASE WHEN b.Word IS NOT NULL OR c.word IS NOT NULL OR d.word IS NOT NULL THEN 1 ELSE 0 END AS Found
From @Test a
LEFT JOIN @Find b ON a.Test = b.Word
LEFT JOIN @Find c ON a.Test2 = c.Word
LEFT JOIN @Find d ON a.Test3 = d.Word
)
Select *
From x
WHERE Found = 1