Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL query- ID not exist in another table or exist but with all records are in history?

Tags:

sql

select

db2

i have table T1

ID
1
2
3

and table T2

ID    HISTORY
1       1
1       1
2       1
2       0 

I must select from T1 all records which does not exist in T2 or exists but all records are in history (history flag =1)

So for this my result will be

1
3

What is the correct SQL query for this? Thanks

like image 581
Veljko Avatar asked Nov 27 '22 14:11

Veljko


2 Answers

try this:

select * from T1
where ID not in(select ID from T2 where HISTORY_FLG!=1)


SQL Fiddle demo

like image 135
Joe G Joseph Avatar answered Dec 04 '22 08:12

Joe G Joseph


Try to use not exists

select * 
from t1 t
where not exists
     (
       select 1
       from t2 a
       where a.id = t.id
       and a.HISTORY <> 1
     )

SQL Fiddle DEMO

like image 33
Robert Avatar answered Dec 04 '22 09:12

Robert