Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to join two tables of mysql and concatenate multiple rows into single cell?

Tags:

php

mysqli

How to join two tables of sql and concatenate multiple rows into single cell?

The Query which i am using::

SELECT Customers.CustomerName, Orders.OrderID
FROM Customers
LEFT JOIN Orders
ON Customers.CustomerID=Orders.CustomerID;

Output which i got::

CustomerName          OrderId

John Doe                                     101

John Doe                                     102

John Doe                                     103

John Doe                                     104

Expected Output::

CustomerName          OrderId

John Doe                            101,102,103,104

like image 722
Yash M. Hanj Avatar asked Apr 13 '18 07:04

Yash M. Hanj


2 Answers

Group concat is the easiest way to achieve the output you require.

like image 140
Hercules Avatar answered Nov 06 '22 17:11

Hercules


Use GROUP_CONCAT and aggregate by customer to generate a CSV list of orders:

SELECT
    c.CustomerName,
    GROUP_CONCAT(o.OrderID) AS OrderIDs
FROM Customers c
LEFT JOIN Orders o
    ON c.CustomerID = o.CustomerID
GROUP BY
    c.CustomerId;

Note that it would be preferable to aggregate by customer ID, if possible, because perhaps two or more customers have the same name.

Demo

like image 30
Tim Biegeleisen Avatar answered Nov 06 '22 18:11

Tim Biegeleisen