多个Like子句按大多数匹配包含
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了多个Like子句按大多数匹配包含相关的知识,希望对你有一定的参考价值。
我有一个AreaMaster表
如果我搜索“AreaName”就像'%New Kant%'那么它应该返回大多数匹配值(行中的第一个记录)
假设
如果我搜索“Sector 26 Navi”它应该返回表格中的最后一条记录
如果我搜索“Sector 45 400706”它应该从表返回第4条记录,最后一条包含扇区字
答案
由于我没有任何SQL Server(并且在Online SQL-Server测试工具上没有启用全文),我无法尝试我的代码。
CREATE TABLE t
([id] int PRIMARY KEY NOT NULL, [first_name] varchar(9), [address] varchar(21))
;
CREATE UNIQUE INDEX UIX_SomeUniqueIdex ON dbo.t(ID);
;
/*Create a Catalog*/
CREATE FULLTEXT CATALOG Test_Catalog AS DEFAULT;
;
/* Finally the FTS Index */
CREATE FULLTEXT INDEX ON t (address)
KEY INDEX UIX_SomeUniqueIdex;
;
INSERT INTO t
([id], [first_name], [address])
VALUES
(1, 'Aura', '2 Clarendon Way'),
(2, 'Horacio', '2503 Hazelcrest Court'),
(3, 'Siana', '68 Emmet Trail'),
(4, 'Lief', '86853 Mesta Plaza'),
(5, 'Alvinia', '1 Fieldstone Street'),
(6, 'Joela', '737 3rd Circle'),
(7, 'Elwin', '1 Oakridge Point'),
(8, 'Nell', '137 Hoffman Crossing'),
(9, 'Julie', '438 Magdeline Avenue'),
(10, 'Abdel', '237 Jackson Hill'),
(11, 'Phylys', '83 Claremont Street'),
(12, 'Ignacius', '4629 Canary Hill'),
(13, 'Emmery', '26 Carey Terrace'),
(14, 'Darrel', '04 Namekagon Pass'),
(15, 'Batsheva', '9021 Hermina Parkway'),
(16, 'Constance', '60 Bluestem Junction'),
(17, 'Wes', '49416 Carey Hill'),
(18, 'Gilda', '7515 Grover Circle'),
(19, 'Nari', '6 Brentwood Junction'),
(20, 'Fabiano', '7216 Artisan Place')
;
选择:
SELECT *
FROM t
WHERE FREETEXT(address, '1 Place');
另一答案
试试这个
DECLARE @MyWord NVARCHAR(50) = 'ABC EFG'
DECLARE @T TABLE
(
Qstn NVARCHAR(255)
)
INSERT INTO @T
VALUES
('ABC EFG'),
('HIJ ABC'),
('XYZ KHJ'),
('HIJ DAS')
;WITH PTN
AS
(
SELECT
RN = ROW_NUMBER() OVER(ORDER BY Qstn),
FullWord = Qstn,
Qstn = LTRIM(RTRIM(SUBSTRING(Qstn,CHARINDEX(' ',Qstn),LEN(Qstn)))),
SpInd = CHARINDEX(' ',Qstn),
MyWord = RTRIM(LTRIM(SUBSTRING(Qstn,1,CHARINDEX(' ',Qstn)))),
WordSpot = 1,
SpcCnt = LEN(Qstn)-LEN(REPLACE(Qstn,' ',''))
FROM @T
UNION ALL
SELECT
RN,
FullWord,
Qstn = LTRIM(RTRIM(SUBSTRING(Qstn,CHARINDEX(' ',Qstn),LEN(Qstn)))),
SpInd = CHARINDEX(' ',Qstn),
MyWord = RTRIM(LTRIM(SUBSTRING(Qstn,1,SpInd))),
WordSpot = WordSpot+1,
SpcCnt = SpcCnt-1
FROM PTN
WHERE SpcCnt > 0
),HIT
AS
(
SELECT
T1.RN,
HITRN = COALESCE(Q.RN,T1.RN)
FROM PTN T1
OUTER APPLY
(
SELECT
T2.RN
FROM PTN T2
WHERE T1.RN <> T2.RN
AND CHARINDEX(T1.MyWord,T2.MyWord)>0
)Q
),RST
AS
(
SELECT
SeqNo = ROW_NUMBER() OVER(PARTITION BY S.FullWord,M.FullWord ORDER BY S.FullWord),
Original = S.FullWord,
PatternMatch = M.FullWord
FROM HIT
INNER JOIN PTN M
ON HIT.RN = M.RN
INNER JOIN PTN S
ON HIT.HITRN = S.RN
and S.FullWord = @MyWord
)
SELECT
*
FROM RST
WHERE SeqNo = 1
以上是关于多个Like子句按大多数匹配包含的主要内容,如果未能解决你的问题,请参考以下文章