i have 4 tables with the following schema.
- Table 1. Iposts ( id, user_id, link,media_url,inst_user_id)
- Table 2. ipostsproduct (id, post_id, product_id)
- Table 3. products ( id, handle)
- Table 4. ipostssf (id, status, profile_picture,name,profile_username )
I am trying to get all the details from Iposts which may have or not have attached more products. If it has, get the detail from products. The code so far :
SELECT ip.*,
sf.profile_picture,
sf.NAME AS page_title,
sf.profile_username,
FROM iposts ip
INNER JOIN ipostssf sf
ON sf.page_id = ip.inst_user_id
LEFT JOIN products p
ON p.id IN
(
SELECT ipp.product_id
FROM ipostproduct ipp
WHERE ipp.id = ip.id)
WHERE ip.user_id = 1
AND sf.status = 1 ');
Tried to select intro an subselect
SELECT ip.*,
sf.profile_picture,
sf.NAME AS page_title,
sf.profile_username,
(SELECT p.*
FROM products p
WHERE p.id IN (SELECT ipp.product_id
FROM ipostsproduct ipp
WHERE ipp.post_id = p.id))
FROM iposts ip
INNER JOIN ipostssf sf
ON sf.page_id = ip.inst_user_id
The final array would be something like
$arr = array(
'profile_picture'=>...,
'page_title' => ....,
'profile_username' => ....,
'products' => array(
'1' => array(
//all the details here
'id'=> ....,
'handle' => ...,
),
'2' => array(
//all the details here
'id'=> ....,
'handle' => ...,
)
)
);
I can do select from iposts inner join ipostssf left join ipostsproduct ( it may have / or not ) but after , it if has, how can i inner join ipostsproduct with products by product id.
P.S The question is not how to retrieve the json/array , is how to do the query so that the results to contain all the products and all the products details from each table using the joins.