[英]select rows based on column1 and column2 that have value of column 1
I have a SQL table like this:我有一个像这样的 SQL 表:
ID, ID2, category. date, txt
1 null 1 Y-m-d text
2 null 1 Y-m-d text
3 4 1 Y-m-d text
4 null 2 Y-m-d text
5 6 1 Y-m-d text
6 null 3 Y-m-d text
7 null 5 Y-m-d text
I try to select all rows with category = 1 like id: 1,2,3,5,6, but also I want row with id 4,6 even if their category is not 1, but they are in ID2 of a row that have category 1.我尝试 select 所有类别 = 1 的行,例如 id: 1,2,3,5,6,但我也想要 id 为 4,6 的行,即使它们的类别不是 1,但它们在 ID2 的行中有类别 1。
Select * from table WHERE category=1 AND .... LIMIT 20
So results will be 1,2,3,4,5,6所以结果将是 1,2,3,4,5,6
You can use exists
你可以使用
exists
select *
from t
where category=1
or exists (select * from t t2 where t2.id2=t.id and t2.category=1)
how you want the result?你想要的结果如何?
first:第一的:
select id t from test a where a.category='1' and id is not null select id t 来自测试 a,其中 a.category='1' 并且 id 不是 null
union all联合所有
select id2 t from test a where a.category='1' and id2 is not null select id2 t 来自测试 a,其中 a.category='1' 和 id2 不是 null
id ![]() |
---|
1 ![]() |
2 ![]() |
3 ![]() |
5 ![]() |
4 ![]() |
6 ![]() |
second:第二:
select a.* from test a left join test b on a.id=b.id where a.category='1' or b.category='1' select a.* from test a left join test b on a.id=b.id where a.category='1' or b.category='1'
id ![]() |
id2 ![]() |
category![]() |
---|---|---|
1 ![]() |
1 ![]() |
|
2 ![]() |
1 ![]() |
|
3 ![]() |
4 ![]() |
1 ![]() |
5 ![]() |
6 ![]() |
1 ![]() |
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.