[英]Grouping one field from several rows of the same table in one result in Mysql and Fat Free Framework
I have three tables in MySQL:我在 MySQL 中有三个表:
CUSTOMERS
+------------+--------------+
| customerId | customerName |
+------------+--------------+
PRODUCTS
+-----------+-------------+
| productId | productName |
+-----------+-------------+
RENTALS
+--------------+--------------+-----------------+
| rentalNumber | rentalAmount | rentalProductId |
+--------------+--------------+-----------------+
The Rentals table has various rows for one rentalNumber. Rentals 表为一个rentalNumber 包含不同的行。 I need to return a result in php like this:我需要像这样在 php 中返回一个结果:
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. RentalDetails 位可能是一个字符串,显示在 HTML 表中。
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 :)不过这对我有用:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.