Php 找到每天最畅销的三种产品

Php 找到每天最畅销的三种产品,php,mysql,Php,Mysql,我想找到每天最畅销的三种产品 将它们与销售额一起显示 但是,如果有多个产品共享同一产品 销售数量我只想告诉你有多少产品得到了这个 排名 我有两张桌子 Products: +-----+---------+ | Pid | Product | +-----+---------+ | 1 | Moon | | 2 | Sun | | 3 | Venus | | 4 | Mars | +-----+---------+ SalesRows: +-----+--

我想找到每天最畅销的三种产品 将它们与销售额一起显示

但是,如果有多个产品共享同一产品 销售数量我只想告诉你有多少产品得到了这个 排名

我有两张桌子

Products:
+-----+---------+
| Pid | Product |
+-----+---------+
|  1  | Moon    |
|  2  | Sun     |
|  3  | Venus   |
|  4  | Mars    |
+-----+---------+

SalesRows:
+-----+---------+------------+
| Pid | No_sold | Sales_date |
+-----+---------+------------+
|  1  |    1    | 2013-01-01 |
|  2  |    5    | 2013-01-01 |
|  3  |    2    | 2013-01-01 |
|  2  |    2    | 2013-01-01 |
+-----+---------+------------+
应提供:

+------+--------------+-------+
| Rank | Product      | Sales |
+------+--------------+-------+
|  1   | Sun          |   7   |
|  2   | Venus        |   2   |
|  3   | Moon         |   1   |
+------+--------------+-------+
+------+--------------+-------+
| Rank | Product      | Sales |
+------+--------------+-------+
|  1   | Sun          |   7   |
|  2   | Venus        |   2   |
|  3   | *2 products* |   1   |
+------+--------------+-------+
但是,此销售数据:

SalesRows:
+-----+---------+------------+
| Pid | No_sold | Sales_date |
+-----+---------+------------+
|  1  |    1    | 2013-01-01 |
|  2  |    5    | 2013-01-01 |
|  3  |    2    | 2013-01-01 |
|  2  |    2    | 2013-01-01 |
|  4  |    1    | 2013-01-01 |
+-----+---------+------------+
应提供:

+------+--------------+-------+
| Rank | Product      | Sales |
+------+--------------+-------+
|  1   | Sun          |   7   |
|  2   | Venus        |   2   |
|  3   | Moon         |   1   |
+------+--------------+-------+
+------+--------------+-------+
| Rank | Product      | Sales |
+------+--------------+-------+
|  1   | Sun          |   7   |
|  2   | Venus        |   2   |
|  3   | *2 products* |   1   |
+------+--------------+-------+
对如何解决这最后一部分有什么建议吗?

试试这个:

SELECT Product,SUM(No_sold) AS sales FROM SalesRows 
LEFT JOIN Products ON Products.Pid = SalesRows.Pid
WHERE Sales_date = '".$today."'
GROUP BY Pid

此查询可能对您有所帮助

SELECT @rownum := @rownum + 1 rownum, 
       t.* 
  FROM (SELECT @rownum:=0) r, 
       (select case when indicator = 1 then Product
else concat( indicator, ' Products') end as Product, sales from (Select *, count(sales) as indicator from (SELECT Product,SUM(No_sold) AS sales FROM SalesRows
JOIN Products ON Products.Pid = SalesRows.Pid
WHERE Sales_date = curdate()
GROUP BY SalesRows.Pid ) a group by sales Order by sales desc) a) t

如果你真的解释了SQL语句,而不是仅仅用勺子喂它,那就更好了。这并不能按等级排序,也不能解决当两个或多个产品获得相同等级时如何表示的问题