php - 如何将sql结果分成不同的html列

标签 php mysql database

我有一张 table :

| s_id | s_date     | s_movie               | s_hour | s_price |
|    1 | 2015-11-11 | The lord of the rings |  11:00 |       5 |
|    2 | 2015-11-11 | The lord of the rings |  11:00 |       4 |
|    3 | 2015-11-11 | The lord of the rings |  11:00 |       4 |
|    4 | 2015-11-11 | Harry Potter          |  12:00 |       5 |
|    5 | 2015-11-11 | Harry Potter          |  12:00 |      13 |
|    6 | 2015-11-11 | Harry Potter          |  12:00 |      13 |
|    7 | 2015-11-11 | Harry Potter          |  12:00 |       5 |

结果:

$result = mysql_query("
    SELECT *
     , count(s_price) as uniq_p 
     , SUM(s_price) as uniq_all 
    from table 
    group 
    by s_movie
     , s_price 
    order 
    by s_movie desc
");

HTML表格显示:

+------------+------------+--------+-----+
| Date       | Movie      | Price  | Sum |
+------------+------------+--------+-----+
| 2015-11-11 | The lord.. | 2 x 4  |   8 |
| 2015-11-11 | The lord.. | 1 x 5  |   5 |
| 2015-11-11 | Harry..    | 2 x 5  |  10 |
| 2015-11-11 | Harry..    | 2 x 13 |  26 |

如何连接这样的结果?

+------------+-------------+---------+---------+-----+    
| Date       | Movie       | Price_1 | Price_2 | Sum |
+------------+-------------+---------+---------+-----+  
| 2015-11-11 | The lord..  |  1 x 5  |  2 x 4  |  13 |
| 2015-11-11 | Harry..     |  2 x 13 |  2 x 5  |  36 |

这是一个 msql 示例: http://sqlfiddle.com/#!2/2c0f4/2

最佳答案

当然,您可以在 php 中完成这一切,这可能是最好的方法。

现在,如果您仍然想在数据库中完成大部分工作,您可以这样做

更新:

SELECT s_date, s_movie, 
       GROUP_CONCAT(CONCAT(price_count, ' x ', s_price) ORDER BY s_price DESC) prices, 
       SUM(s_price * price_count) price_sum
  FROM
(
  SELECT s_date, s_movie, s_price, COUNT(*) price_count, SUM(s_price) price_sum
    FROM table1
   GROUP BY s_date, s_movie, s_price
) q
 GROUP BY s_date, s_movie DESC

这将为您提供以下信息:

+---------------------+-----------------------+--------------+-----------+
| s_date              | s_movie               | prices       | price_sum |
+---------------------+-----------------------+--------------+-----------+
| 2015-11-11 00:00:00 | The lord of the rings | 1 x 5,2 x 4  |        13 |
| 2015-11-11 00:00:00 | Harry Potter          | 2 x 13,2 x 5 |        36 |
+---------------------+-----------------------+--------------+-----------+

这里是SQL Fiddle演示

现在,您可以在迭代结果集时通过 ,explode() prices 列值。

关于php - 如何将sql结果分成不同的html列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34816351/

相关文章:

php - 使用 PHP 从 MySQL 获取信息时遇到问题

php - Joomla 中的简单 "loop"

javascript - POST HTML图像对象作为文件

php - 从 php 数组中打印出值

PHP - 按列数组到 CSV

MySQL更改数据库排序规则

php - 使用 JQuery 和 Ajax 进行动态相关选择

mysql - 在存储过程调用中获取未知列 ID

mysql - 在 SQL 中将列名定义为另一个名称?

python - 如何将大表(超过 1 亿行)导出到文本文件?