我正在尝试在sqlite中创建一个查询,该查询将返回: 始于,然后包含
因此“ bou”将返回:
弹跳
弹回
关于我
想着你
等
我尝试使用带有和不带有ORDER BY的LIKE'search%'和LIKE'%search%'的联合来组合查询 但我不知道。我希望能够快速高效地完成一些工作,而又不能创建2个不同的查询/结果并手动组合。 有任何想法吗? 谢谢
答案 0 :(得分:1)
我相信以下内容可能会满足您的要求或接近您的要求:-
WITH cte1(search_item) AS (SELECT 'bou') -- <<<<<<<<<< search argument
SELECT
CASE
WHEN mytext LIKE (select search_item FROM cte1)||'%'
THEN mytext||' - begins with '||(select search_item FROM cte1)
ELSE
mytext||' - includes '||(select search_item FROM cte1)
END AS phrased,
mytext
FROM mytable
WHERE mytext LIKE '%'||(select search_item FROM cte1)||'%';
因此,使用以下内容作为测试:-
DROP TABLE IF EXISTS mytable;
CREATE TABLE IF NOT EXISTS mytable (mytext TEXT);
INSERT INTO mytable VALUES
('Bounce'),
('Bounce Back'),
('About Me'),
('About You'),
('Something Else'), -- ADDED to prove not found result
('Thinking About You')
;
WITH cte1(search_item) AS (SELECT 'bou') -- <<<<<<<<<< search argument
SELECT
CASE
WHEN mytext LIKE (select search_item FROM cte1)||'%'
THEN mytext||' - begins with '||(select search_item FROM cte1)
ELSE
mytext||' - includes '||(select search_item FROM cte1)
END AS phrased,
mytext
FROM mytable
WHERE mytext LIKE '%'||(select search_item FROM cte1)||'%';
结果:-
但是,以下内容可能更符合您的要求(即根据找到的数据是否以sreach参数开头或包含sreach参数进行排序):-
WITH
cte1(search_item) AS (
SELECT 'bou' -- <<<<<<<<<< search argument
),
cte2(phrased,ordering,mytext) AS (
SELECT
CASE
WHEN mytext LIKE (select search_item FROM cte1)||'%'
THEN mytext||' - begins with '||(select search_item FROM cte1)
ELSE
mytext||' - includes '||(select search_item FROM cte1)
END AS phrased,
CASE
WHEN mytext LIKE (select search_item FROM cte1)||'%'
THEN 0
ELSE 1
END AS ordering,
mytext
FROM mytable
WHERE mytext LIKE '%'||(select search_item FROM cte1)||'%'
)
SELECT mytext, phrased FROM cte2 ORDER BY ordering;
;
结果为:-