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 );