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
239 views
in Technique[技术] by (71.8m points)

Simple way to write SQL query for select all data of linked tables in PostgreSQL

I want to return the data of all the tables linked together via foreign keys when the tables are linked together in a chain. Is there a simple SQL command for this?

SAMPLE DATA: A entrance has floor_id fk to floors table, floor table has a building_id fk to buildings, buildings has a company_id fk to companies.

Can I get all the above data given just the entrance id?

Is there a more elegant way to do this then the following SQL:

    SELECT * FROM floor_entrance 
    LEFT JOIN floor ON floor.id = (SELECT floor_id FROM floor_entrance WHERE id = {floor_entrance_id})
    LEFT JOIN building ON building.id = (SELECT building_id FROM floor WHERE id = 
        (SELECT floor_id FROM floor_entrance WHERE id = {floor_entrance_id}))
    LEFT JOIN company ON company.id = (SELECT company_id FROM building WHERE id = 
        (SELECT building_id FROM floor WHERE id = 
            (SELECT floor_id FROM floor_entrance WHERE id = {floor_entrance_id})))
    WHERE floor_entrance.id = {floor_entrance_id}

I am looking to achieve a concise way to write this postgreSQL command.

DESIRED RESULTS: "LEFT JOIN ALL ON FOREIGN KEYS ACROSS THE WHOLE SCHEMA"?

question from:https://stackoverflow.com/questions/65863542/simple-way-to-write-sql-query-for-select-all-data-of-linked-tables-in-postgresql

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

1 Reply

0 votes
by (71.8m points)

I would simply do it like this

SELECT * FROM floor_entrance A
LEFT JOIN floor B ON A.floor_id = B.id 
LEFT JOIN building C ON B.building_id = C.id 
LEFT JOIN company D ON C.company_id = D.id 
WHERE A.id = {floor_entrance_id}

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

...