我需要在小内容表中实现简单搜索:id,name,description,content。 结果必须按优先顺序排列
这意味着如果在描述字段中找到搜索词,则只会在名称字段中具有dog的所有行之后显示
我做了什么:
我尝试创建临时表,其结构类似于我使用的表,但具有另一个字段优先级。对于每个字段,我用于搜索,插入选择到临时表
示例:
DECLARE @query NVARCHAR(255)
CREATE TABLE #tbl_search
(
[id] INT NOT NULL ,
[name] NVARCHAR(255) ,
[description] NVARCHAR(MAX) ,
[content] NVARCHAR(MAX) ,
[priority] INT
)
--searching in name field
INSERT INTO #tbl_search
( [ID] ,
[name] ,
[description] ,
[content] ,
[priority]
)
SELECT [ID] ,
[name] ,
[description] ,
[content] ,
1
FROM [tbl_content]
WHERE name LIKE '%' + @query + '%'
--searching in description field
INSERT INTO #tbl_search
( [ID] ,
[name] ,
[description] ,
[content] ,
[priority]
)
SELECT [ID] ,
[name] ,
[description] ,
[content] ,
2
FROM [tbl_content]
WHERE description LIKE '%' + @query + '%'
AND id NOT IN ( SELECT id
FROM #tbl_search )
--.....
SELECT *
FROM #tbl_search
ORDER BY [priority]
DROP TABLE #tbl_search
答案 0 :(得分:4)
执行此操作的一种方法是使用CASE关键字:
SELECT name, description, content,
priority = CASE
WHEN name LIKE '%' + @query + '%' THEN 1
WHEN desription LIKE '%' + @query + '%' THEN 2
WHEN content LIKE '%' + @query + '%' THEN 3
END CASE
FROM tbl_content
WHERE
name LIKE '%' + @query + '%' OR
desription LIKE '%' + @query + '%' OR
content LIKE '%' + @query + '%'
ORDER BY priority ASC
答案 1 :(得分:1)
最简单的方法是使用UNION查询:
SELECT name AS text FROM tbl_content WHERE name LIKE '%' + @query + '%'
UNION
SELECT description AS text FROM tbl_content WHERE desription LIKE '%' + @query + '%'
UNION
SELECT content AS text FROM tbl_content WHERE content LIKE '%' + @query + '%'
答案 2 :(得分:0)
为了完整起见,我使用@order子句(查询mysql)的情况将@Amirshk出色的解决方案移到了下一个级别:
SELECT name, description, content
FROM tbl_content
WHERE
name LIKE '%' + @query + '%' OR
desription LIKE '%' + @query + '%' OR
content LIKE '%' + @query + '%'
ORDER BY CASE
WHEN name LIKE '%' + @query + '%' THEN 1
WHEN desription LIKE '%' + @query + '%' THEN 2
WHEN content LIKE '%' + @query + '%' THEN 3
END