Jithin Varghese
Jithin Varghese

Reputation: 2228

how to get values from 2 tables based on common table

//Table 1 (favourite)

id || user_id || event_id || news_id
1        1          1           0
2        1          0           1

//Table 2 (event)

event_id || name || location || descr
   1        jit       ekm       demo 

//Table 3 (news)

 news_id || title || news || location
    1       Demo      no       thr

My question is from Table 1, when news_id field is 0 then display values from Table 2 according to event_id values in Table 1 and when event_id field is 0 then display values from Table 3 according to news_id values in Table 1.

Is this possible. How to make this.

Upvotes: 1

Views: 44

Answers (1)

dsojevic
dsojevic

Reputation: 1096

This should probably do the trick for you-- it's joining the tables based on the values present in the favourite table:

SELECT    f.id, f.user_id,
          e.event_id, e.name event_name, e.location event_location, e.descr event_descr,
          n.news_id, n.title news_title, n.news, n.location news_location
FROM      favourite f
LEFT JOIN event e ON e.event_id = f.event_id
LEFT JOIN news  n ON n.news_id  = f.news_id

Upvotes: 4

Related Questions