[英]SQLite Add content from other table if limit has not been reached
I have a quick question.我有一个快速的问题。 I have two SQLite tables like the following:
我有两个 SQLite 表,如下所示:
TableOne
id ![]() |
rowone![]() |
---|---|
1 ![]() |
rowone_content_a ![]() |
2 ![]() |
rowone_content_ab ![]() |
3 ![]() |
rowone_content_ac ![]() |
4 ![]() |
rowone_content_bc ![]() |
TableTwo
id ![]() |
rowone![]() |
rowtwo![]() |
---|---|---|
1 ![]() |
rowone_content_a ![]() |
a![]() |
2 ![]() |
rowone_content_ab ![]() |
ab![]() |
3 ![]() |
rowone_content_ac ![]() |
ac![]() |
4 ![]() |
rowone_content_bc ![]() |
bc![]() |
So I want a SQL that has the following behavior:所以我想要一个具有以下行为的 SQL:
Search: tent_a
(something that contains tent_a
somewhere).搜索:
tent_a
(某处包含tent_a
的东西)。
When I search for it, I want the following result:当我搜索它时,我想要以下结果:
rowname that doesn't matter![]() |
from table (not included in the output)![]() |
---|---|
a![]() |
TableTwo |
ab![]() |
TableTwo |
ac![]() |
TableTwo |
rowone_content_a ![]() |
TableOne |
rowone_content_ab ![]() |
TableOne |
Background is that I have a search that should first look in the first row of the second table and select the value of the second row if the value of the first row contains the text I am looking for, limited by 5. But if the data returned from table two is less than 5, the SQL should fill the empty fields with data found in table one.背景是我有一个搜索应该首先查看第二个表的第一行和 select 第二行的值,如果第一行的值包含我要查找的文本,限制为 5。但是如果数据从表二返回小于 5,SQL 应使用表一中的数据填充空白字段。
Thanks for any help.谢谢你的帮助。
I think you want union all
:我想你想要
union all
:
select rowone, 'tableone'
from tableone
where rowone like '%tent\_a%'
union all
select rowtwo, 'tabletwo'
from tabletwo
where rowone like '%tent\_a%'
Use UNION ALL
to get all the rows from the 2 tables that satisfy your conditions and then Use ORDER BY
and LIMIT
to return only the first 5 rows:使用
UNION ALL
从满足您的条件的 2 个表中获取所有行,然后使用ORDER BY
和LIMIT
仅返回前 5 行:
SELECT rowname
FROM (
SELECT rowtwo rowname, 1 fromtable
FROM TableTwo
WHERE rowone LIKE '%tent\_a%' ESCAPE '\'
UNION ALL
SELECT rowone, 2
FROM TableOne
WHERE rowone LIKE '%tent\_a%' ESCAPE '\'
)
ORDER BY fromtable, rowname LIMIT 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.