简体   繁体   中英

How to create a View with 4 tables?

I have four tables

Table 1
-------------
primary key-pk1


Table 2
------------
primary key-pk2
foreign key-pk1


Table 3
------------
primary key-pk3
foreign key-UID


Table 4
------------
primary key-pk4
foreign keys-pk1,UID,pk3


Table U
------------
primary key-UID

I wanted to create a View with tables Table 1, Table 2, Table 3 and Table 4 in such a way that even if there is no contents in Table 2 and Table 3, I should get join ,ie matching contents, of Table 1 and Table 4.

There will always be contents in Table 1 and Table 4. Table 2 and Table 3 may or may not have contents

Thanks in advance :)

Try using left join. Should work somewhat like this:

SELECT *  
FROM TABLE_1 tb1
JOIN TABLE_4 tb4 ON tb1.pk1 = tb4.pk1
JOIN TABLE_U tbU ON tb4.UID = tbU.UID
LEFT JOIN TABLE_2 tb2 ON tb1.pk1 = tb2.pk1
LEFT JOIN TABLE_3 tb3 ON tb4.UID = tb3.UID

By the way, try listing all fields you actually need instead of using "SELECT *", since it's better for readability and performance.

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