1

I need help with a simple SQL query. Suppose I have two tables, customers and orders. In customers table I have only name and id fields and in orders table I have name, id and customer_id fields. Here customer_id is the foreign key to customers table.

So now I want to fetch all customers and also join each of their orders. Suppose these are the two tables with dummy data:

customers table

id                         name
1                          John Doe
2                          Jane Doe
orders table
id                         product_name               customer_id
250                        Massage Gun                1
260                        Mac Lipstick               2
270                        Mac Eyeliner               2
280                        Yoga Mat                   1
290                        Mac Eyeshadow              2

Here's the code:

const query = `
        SELECT * FROM customers c WHERE EXISTS (SELECT * FROM orders o WHERE o.customer_id = c.id);
`;
const customers = await pool.query( query );
console.log( customers );
s.khan
  • 297
  • 1
  • 7
  • 24
  • Follow this answer https://stackoverflow.com/questions/13227142/using-row-to-json-with-nested-joins – Anand Sowmithiran Jan 12 '22 at 17:19
  • @AnandSowmithiran I don't actually need to map the result to json. I think ```pg``` npm package does that for us which is accessible via ```customers.rows```. I just need the query statement. – s.khan Jan 12 '22 at 17:28

2 Answers2

0

Your SQL statement performs a semi-join, which only checks the existence of orders, but does not include them in the result set. You want a join:

SELECT * FROM customers c JOIN orders o
           ON o.customer_id = c.id
Heiko Theißen
  • 12,807
  • 2
  • 7
  • 31
0
// construct your query 1st
const query = `SELECT c.*, o.id as orderId, o.product_name 
               FROM customers c 
               INNER JOIN orders o 
               ON(c.id = o.customer_id);`;
// try-catch pool.query since it can raise exception
try{     
  const customers = await pool.query(query);
  let customers_dict = {};
  for(var i = 0; i<customers.length; i++){
     if(!(customers[i].id.toString() in customers_dict)){ // 1st order
      customers_dict[customers[i].id.toString()] = {
         "id": customers[i].id,
          "name": customers[i].name,  
          "orders":[
                    {
                      "id": customers[i].orderId,
                      "product_name":customers[i].product_name,
                    }
                   ]
         }; 
    }else{  // another order for the customer id
      customers_dict[customers[i].id.toString()]["orders"].push({
                       "id": customers[i].orderId,
                       "product_name": customers[i].product_name,
                    });      
   }
 }
    
 //here is the expected final json result
 const expected_json_customers = Object.values(customers_dict);
 console.log(expected_json_customers);     
}catch(err){
   console.log(err); // your error mgmt function
}