Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Join 4 tables in SQL query

Have 4 relationship tables in my database and want to join them to get the total value... for instance i have friends, family, following and acquaintances and want to join these to get an "ALL" value.

The table formats are as such:

Friends

id follower following
---------------------
1     2      3
2     4      5

Family

id follower following
---------------------
1     5      6
2     7      8

Following

id follower following
---------------------
1     9      10
2     11     12

Acquaintances

id follower following
---------------------
1     13     14
2     15     16

Is the correct query to join all 4 tables...

SELECT following
FROM   friends
       INNER JOIN family ON friends.following=family.following
       INNER JOIN following ON friends.following=following.following
       INNER JOIN acquaintances ON friends.following=acquaintances.following
WHERE  follower='id'

Basically I want to join and retrieve the "following" value from all four tables where id= my id

like image 626
user946742 Avatar asked Feb 21 '23 03:02

user946742


1 Answers

Your current query will only list a result if all tables have a link with your friends table. I believe you are more looking for something like this

SELECT following
FROM   friends
WHERE  follower='id'
UNION ALL 
SELECT following
FROM   family 
WHERE  follower='id'
UNION ALL 
SELECT following
FROM   following
WHERE  follower='id'
UNION ALL 
SELECT following
FROM   acquaintances 
WHERE  follower='id'

or a bit nicer to read and easier to adjust at the cost of some performance

SELECT following 
FROM   (
        SELECT following, follower FROM friends
        UNION ALL SELECT following, follower FROM family 
        UNION ALL SELECT following, follower FROM following
        UNION ALL SELECT following, follower FROM acquaintances 
       ) AS f
WHERE  follower='id'

UNION

UNION is used to combine the result from multiple SELECT statements into a single result set.

like image 129
Lieven Keersmaekers Avatar answered Mar 05 '23 19:03

Lieven Keersmaekers