Grouping one field from several rows of the same table in one result in Mysql and Fat Free Framework

77 views Asked by At

I have three tables in MySQL:

CUSTOMERS
+------------+--------------+
| customerId | customerName |
+------------+--------------+

PRODUCTS
+-----------+-------------+
| productId | productName |
+-----------+-------------+

RENTALS
+--------------+--------------+-----------------+
| rentalNumber | rentalAmount | rentalProductId |
+--------------+--------------+-----------------+

The Rentals table has various rows for one rentalNumber. I need to return a result in php like this:

RESULT
+--------------+--------------+----------------------------------+
| customerName | rentalNumber | rentalDetails                    |
+--------------+--------------+----------------------------------+
| Johnny       | 20           | productName1 x productAmount1,   |
|              |              | productName2 x productAmount 2,  |
|              |              | productName3 x productAmount 3   |
+--------------+--------------+----------------------------------+

the rentalDetails bit may be a string, displayed in a HTML table.

1

There are 1 answers

0
vanMeerdervoort On BEST ANSWER

While fiddling along I found the answer eventually:

SELECT *, group_concat(concat(`productName`,' x ',`rentalProductAmount`) separator ',') AS items
FROM rentals
LEFT JOIN customers on rentals.rentalCustomer = customers.customerId
LEFT JOIN products ON rentals.rentalProduct = products.productId
WHERE rentals.rentalStartDate >= NOW()
GROUP BY rentals.rentalNumber

But perhaps there's an even better way. This works for me though :)