繁体   English   中英

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

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

我在 MySQL 中有三个表:

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

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

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

Rentals 表为一个rentalNumber 包含不同的行。 我需要像这样在 php 中返回一个结果:

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

RentalDetails 位可能是一个字符串,显示在 HTML 表中。

在摆弄的过程中,我最终找到了答案:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM