将同一 table 的几行中的一个字段分组为一个结果 Mysql 和 Fat Free Framework

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

我在 MySQL 中有三个 table:

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

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

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

出租 table 有一个 rentalNumber 的不同行。 我需要 return 在 php 中得到这样的结果:

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

rentalDetails 位可能是一个字符串,显示在 HTML table.

一路摸索终于找到答案:

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

但也许还有更好的方法。不过这对我有用:)