簡體   English   中英

PHP-MySQL:多次分組

[英]PHP-MySQL : Multiple Group By and while

我是使用PHP和MySql自學的。 我面臨一個我無法理解的問題:我的數據庫包含以下字段:-日期-小時-電子郵件-產品-數量每次客戶購買產品時,我都會在數據庫中記錄以上列出的信息。 (每個產品一行)。 如果客戶同時購買多個產品,則日期,時間和電子郵件相同。

我的願望是:如果日期,時間和電子郵件相同,並且為這三部分信息購買了所有產品,我將在一行中的表格中收集日期,時間和電子郵件。

我的問題如下:我使用查詢:SELECT * FROM CUSTOMER GROUP BY日期,時間,電子郵件“然后我在表中分配”,而“”。

MySQL組正確記錄了“日期”,“小時”和“電子郵件”,但產品顯示不一致。

這是我的代碼:

$query_customer = "SELECT * FROM CLIENT GROUP BY date, hour, email";
mysql_query($query_customer) or die('Error customer table '.$query_customer.' <br/>'.mysql_error());
$result_customer=mysql_query($query_customer);

    $row_customer = '';
    $name_product = '';
    $quantity_product = '';

    while($distribution_customer = mysql_fetch_array($result_customer))
    {
    $email = '<span>'.$distribution_customer['email'].'</span>';
    $date = $distribution_customer['date'].' at '.$distribution_customer['hour'];
    $quantity_product .= '(x'.$distribution_customer['quantity'].')';
    $name_product .= '<span>'.$distribution_customers['product'].'</br> '.$quantite_produit.'</span>';

    $row_customer .= '
            <tr>
                <td>'.$date.'</td>
                <td>'.$email.'</td>
                <td>'.$name_product.'</td>
            </tr>
        ';
    }
        <table>
        <?php echo $row_customer ?>
        </table>

我認為我離解決方案不遠,但我找不到攻角。 也許有人會幫助我更清楚地看到? 我應該使用“ group_concat”嗎?

非常感謝您的見解。

您面臨的問題是由於數據庫中缺乏規范化。 例如,如果您有一個table (不是您所寫的數據庫),其中包含"username", "password", "email", other user-related columns, "product name", "product description", "product price", other product-related columns, "quantity", "date" etc ,您的數據庫中將有很多冗余信息,並且在需要更新此數據時會感到頭疼。 請注意,這是一個誇大的例子。

為了防止信息在數據庫中冗余,您需要設計表,使它們至少為3NF(請參閱http://en.wikipedia.org/wiki/Third_normal_form )。 您的數據庫必須包含4個表:

user (id, username, password, email, ...)
product (id, productName, productDescription, price, ...)
cart (id, user_id, date, totalValue, totalNumberOfItems, delivered, ...)
cart_items (id, cart_id, product_id, quantity, ...)

...然后從這些表中選擇內容如下:

select * from user, product, cart, cart_items where user.id=cart.user_id and product.id=cart_items.product_id and cart.id=cart_items.cart_id and cart.delivered=0 group by cart.id sort by user.username asc;

問候

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM