mysql group by方法

时间:2013-03-22 04:23:54

标签: php mysql

购买表:

========================
id|username|product|price|
01|Desmond |tv     |$40  |
02|Desmond |watch  |$20  |
03|Desmond |ring   |$30  |
04|Desmond |laptop |$40  |
========================

产品表:

============================
id|product|type |promotion_ID|
01|tv     |big  |001         |
02|watch  |small|002         |
03|ring   |small|002         |
04|laptop |big  |001         |
============================

促销ID:

==============================
id|promotion_ID|promotion_name|
01|001         |mid-year      |
02|002         |end-year      |
==============================

我想基于while循环方法显示来自Purchase表的结果,以显示来自mysql的所有信息,这是没有问题的,但我想根据购买表对它们进行分组,相应于它们的促销ID /促销名称。我可以知道,我该怎么办呢?

例如 显示结果:

年中

=======================
username|product|price|
Desmond |tv     |$40  |
Desmond |laptop |$40  |
=======================

结束年

=======================
username|product|price|
Desmond |watch  |$20  |
Desmond |ring   |$30  |
=======================

3 个答案:

答案 0 :(得分:0)

您是否只是在寻找ORDER BYJOIN

SELECT promotion_name, 
    username, 
    p.product,
    price
FROM Purchase P
    JOIN Product PR ON P.Product=PR.Product
    JOIN Promotion PO ON PR.Promotion_Id=PO.Promotion_Id
ORDER BY promotion_name, p.product

关于您的数据库,我不建议将产品存储在购买表中 - 您应该存储Product_Id。

答案 1 :(得分:0)

This may help you..

Select username,product,price from Purchase
Join Product on Product.product = Purchase.product 
Join Promotion On promotion.promotion_ID  = Product.promotion_ID
where promotion_name = 'mid-year' // pass your argument
Order by Product.product

答案 2 :(得分:0)

SELECT pur.username, pur.product, pur.price
FROM tbl_purchase pur 
INNER JOIN tbl_product pro USING(product)
INNER JOIN tbl_promotion prm USING(promotion_ID)
ORDER BY prm.promotion_name

注意:您没有在所有表格中引用主键,因此请在所有表格的product列和promotion_id列上制作索引