簡體   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