我有两个表用于存储图像及其相关的 exif 数据:
image_table
有如下记录:
(query: select * from image_table where order_id = 3030303)
image_exif_info
表有如下记录:
(query: select * from image_exif_info where
image_id in (select image_id from image_table where order_id = 3030303)
如第二个屏幕截图中所示,我对 Make
和 Model
字段感兴趣。
我想做的是编写一个查询来显示这样的数据(报告):
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/