php - 直接从Mysql查询数据生成报告(使用groupby、count)

标签 php mysql sql group-by aggregate-functions

我有两个表用于存储图像及其相关的 exif 数据:

image_table 有如下记录:

(query: select * from image_table where order_id = 3030303)

enter image description here

image_exif_info 表有如下记录:

(query: select * from image_exif_info where 
image_id in (select image_id from image_table where order_id = 3030303)

enter image description here

如第二个屏幕截图中所示,我对 MakeModel 字段感兴趣。

我想做的是编写一个查询来显示这样的数据(报告):

Make          Model              # of photos
Canon         CanonEOS 400D      (200)
Nikon         Nikon D3200        (120)
....          .....              ....

我知道我可以编写一个查询并循环并进行计数等来获取此报告。然而,我正在努力提高我的 SQL 技能,因此我尝试使用单个查询创建此报告。

到目前为止我已经做到了:

select distinct i.value,count(i.image_id) from image_exif_info i 
where (i.key ='Make' or i.key = 'Model')
and i.image_id in (select image_id from image where order_id =303030)
group by value

上面查询的结果是:

Canon                 200
CanonEOS 400D         200
Nikon                 120
Nikon D3200           120

我希望它与我上面在(报告)下显示的内容相同

最佳答案

这是使用表子查询来完成此操作的一种方法。

SELECT exif.Make, exif.Model, COUNT(i.image_id) AS "# of photos"
FROM image_table i
INNER JOIN (SELECT x.image_id, 
       MAX(CASE WHEN x.`key`='Make' THEN x.`value` ELSE '' END) AS Make,
       MAX(CASE WHEN x.`key`='Model' THEN x.`value` ELSE '' END) AS Model
      FROM image_exif_info x
      WHERE x.`key` IN ('Make','Model')
      GROUP BY x.image_id) exif
ON i.image_id = exif.image_id
GROUP BY exif.Make, exif.Model;

SQLFiddle:http://sqlfiddle.com/#!9/38dc4/11

子查询是一个数据透视表,它给出每个 image_id 以及品牌和型号。然后通过 image_id 将其连接到 image_table,并按品牌和型号进行分组。

关于php - 直接从Mysql查询数据生成报告(使用groupby、count),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30466430/

相关文章:

php - 重定向功能不起作用

PHP/MySQL 问题 : Incorrect integer value: '' for column 1

php - 单行数据库的随机输出

sql - 使用联合或连接 - 哪个更快

php - 多个 foreach 与多个 if inside foreach

php - 从 symfony 任务获取应用程序/模块上下文

php - 将 session 变量从 html 表单传递到多个 php 页面 url?

mysql - 这个 PDO 'Month... Between' 查询有什么问题?

php - 如何转换时间 php 以便将 PT 转换为 CT

sql - PostgreSQL 事务 DDL 和 to_regclass