简体   繁体   中英

How to join tables based on the column value in a table

I have the table news_feed in which all of my different types of activities data will be stored like admin activities, user activities, company activities etc. The table format looks like:

news_id | type    | admin_id | user_id | company_id 
 1      | admin   |    2     |    3    |     0       
 2      | user    |    3     |    4    |     1      
 3      | company |    0     |    1    |     2      

Suppose a user with an id 1 has liked the company which has id 2 then the record will be inserted like

 4       user       0         1         2

And I'm listing them in my module and the listing is perfect. But suppose if the company id 2 doesn't exist or if it is inactive, then the news_feed block in listing getting empty. What I want to do is:

  1. If the type is company then JOIN the company table while select listing with condition for status as active

  2. If the type is user then JOIN the user table while select listing with condition for status as active

Well you can use UNION for this issue

SELECT t.column1, t.column2, t.column3
FROM my_table t INNER JOIN company_table c
ON t.company_id = c.id
WHERE c.active=1 AND t.type = "company"
UNION
SELECT column1, column2, column3
FROM my_table t INNER JOIN user_table u
ON t.user_id = u.id
WHERE c.active=1 AND t.type = "user"  

Just to add, to increase the efiiciency use UNION ALL rather than UNION (or UNION DISTINCT) as UNION requires internal temporary table with index (to skip duplicate rows) while UNION ALL will create table without such index, but keep in mind it will skip the repeated data.

But more optimized way to do a Conditional Join in MySQL by using a INNER JOIN

SELECT t.column1, t.column2, t.column3
FROM  my_table t
INNER JOIN company_table c
ON (t.company_id = c.id AND t.type = "company" AND c.active=1)
INNER JOIN user_table u
ON (t.user_id = u.id AND t.type = "user" AND u.active=1);

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