I am building a social media news aggregation web app in PHP and MySQL. It needs to map various URLs (column url) to specific trends (column trend_id). Here's my dummy data structure:
I need to build a query to fetch URLs for a particular trend_id (for example 12). This is simple:
SELECT
url
FROMurl_table
WHEREtrend_id
= '12'
Now, some trends are related to a specific parent trend. For example trend_ids 12,16 and 45 are related to a parent trend_id 12. So here's my query:
SELECT '12' as
parent_trend_id
,url
FROMurl_table
WHERE (trend_id
= '12' ORtrend_id
= '16' ORtrend_id
= '45')
Here's another example of similar query:
SELECT '345' as
parent_trend_id
,url
FROMurl_table
WHERE (trend_id
= '345' ORtrend_id
= '457' ORtrend_id
= '16')
The issue is that there are multiple such parent - child relationships between trends. As of now I run a for loop within PHP and execute multiple queries. Also, given the nature of my app the parent trend cannot be a part of this table. Is there a way to have a single query which clubs multiple such queries?
Edit:
I have a separate table defining child relationships. It's a simple 3 column table with ID,trend_id (parent) and related_trend_id (child). However, one related_trend_id (child) can have multiple trend_ids (parents). Here's a snapshot of the relations table: