Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
245 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 Reply

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...