Home > database >  Select name of customers and orders
Select name of customers and orders

Time:09-27

I have 2 tables: customers, orders_details. I need to select product_name by one customer. How can I do it

 --------- ---------- 
|  cus_id | name     |
 --------- ---------- 
|       1 | Jimmy    |
|       2 | Anna     | 
 --------- ---------- 
And this is table order_details:

 ---- ------------- ------------- 
| id |  cus_id     |product_name |
 ---- ------------- ------------- 
|  1 | 1           | iPhone 12   |
|  2 | 1           | Macbook Pro |
|  3 | 2           | iPhone 12   |
 ---- ------------- ------------- 

Result i want to :( Please help.

 ---- ------------- -------------------------- 
| id |  cus_id     |     product_name         |
 ---- ------------- -------------------------- 
|  1 | 1           | iPhone 12, Macbook Pro   |
|  2 | 2           | iPhone 12                |
 ---- ------------- -------------------------- 

CodePudding user response:

This query seems will help you

SELECT cus_id, od.id, od.product_name FROM customers
LEFT JOIN orders_details od ON od.cus_id = customers.cus_id

CodePudding user response:

Here is the query.

You can use GROUP_CONCAT and GROUP BY to achieve this.

SELECT cust_id, GROUP_CONCAT(product_name) as product_name FROM `order_details` GROUP BY cust_id;

It should work for you.

Here's the output: https://prnt.sc/1tsm8d8

  • Related