简体   繁体   中英

select rows based on column1 and column2 that have value of column 1

I have a SQL table like this:

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 * from table WHERE category=1 AND ....  LIMIT 20

So results will be 1,2,3,4,5,6

Use a self join here:

SELECT t1.*
FROM yourTable t1
LEFT JOIN yourTable t2
    ON t2.ID2 = t1.ID
WHERE
    t1.category = 1 OR t2.category = 1;

下面演示链接的屏幕截图

Demo

You can use 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

union all

select id2 t from test a where a.category='1' and id2 is not 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'

id id2 category
1 1
2 1
3 4 1
5 6 1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM