1

i have 4 tables with the following schema.

  1. Table 1. Iposts ( id, user_id, link,media_url,inst_user_id)
  2. Table 2. ipostsproduct (id, post_id, product_id)
  3. Table 3. products ( id, handle)
  4. 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.

Mike X
  • 129
  • 1
  • 7
  • The question is not how to create an json is how can i get all the products details. That json/array will be the mysql_fetch_assoc , based on the result from the mysql_query. But as how to get all the products ( not just 1 , 1 is retrieved using left join ), and for all those products , get all the products details. – Mike X Dec 10 '18 at 15:20

0 Answers0