Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
254 views
in Technique[技术] by (71.8m points)

SQL three table joins using two ids and another column

I have three tables

t1    t2     t3

I want to select data from only two of the tables but need the ids and columns from other tables for reference.

How to select data from t3 and t2

WHERE t1.id = t2.id = t3.id
  AND t1.fid = t2.fid = t3.fid 
  AND t1.type = 'abc'

id column will be the same value for all tables. fid column will have incremental fid's but need the ones where t1.type = 'abc' also

Would this work?

select data 
from t3 

select data 
from t2 
join on t1.id = t2.id and t2.id = t3.id 
join on t1.fid = t2.fid and t2.fid = t3.fid and t1.type = 'abc'
where id = 1
question from:https://stackoverflow.com/questions/65839624/sql-three-table-joins-using-two-ids-and-another-column

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Generally, this kind of problem can be solved using EXISTS as follows:

select data 
from t2 
join t1 on t1.id = t2.id and t1.fid = t2.fid
where exists (select 1 from t3 where t2.id = t3.id and t2.fid = t3.fid)
  and t1.type = 'abc'
  and t1.id = 1

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...