我有带有属性 pictureId、albumName、isCover 图片的表格图片。
+--------+-----------+----------+
| id | albumName | coverPic |
+--------+-----------+----------+
| String | String | Boolean |
+--------+-----------+----------+
我需要编写查询来获取每个专辑中的图片数量并获取每个专辑的封面图片的 ID。我写了这个查询,我得到了一些照片,但我不知道如何获取每个专辑的封面图像的 ID。
SELECT ALBUM as album, count(ALBUM) as picsInAlbum, PICTURE_ID as pictureId
FROM PICTURES
group by ALBUM, PICTURE_ID
例如:
+--------+-----------+----------+
| id | albumName |isCover |
+--------+-----------+----------+
| 1 | test | true |
+--------+-----------+----------+
+--------+-----------+----------+
| 2 | test | false |
+--------+-----------+----------+
+--------+-----------+----------+
| 3 | test1 | true |
+--------+-----------+----------+
+--------+-----------+----------+
| 4 | test1 | false |
+--------+-----------+----------+
+--------+-----------+----------+
| 5 | test2 | true |
+--------+-----------+----------+
+--------+-----------+----------+
| 6 | test2 | false |
+--------+-----------+----------+
作为查询结果,我需要这个。
+--------+-----------+----------+
| ALBUM |PICSINALBUM|coverPicId
+--------+-----------+----------+
+--------+-----------+----------+
| test | 2 | 1 |
+--------+-----------+----------+
+--------+-----------+----------+
| test1 | 2 | 3 |
+--------+-----------+----------+
+--------+-----------+----------+
| test2 | 2 | 5 |
+--------+-----------+----------+
最佳答案
条件聚合。对每一行进行测试以确定该行是否是专辑的“封面图片”。如果是,则返回picture_id,否则返回NULL。然后使用聚合函数选出非 NULL 值。
类似这样的事情:
SELECT p.album AS album
, COUNT(p.album) AS picsInAlbum
, MAX(IF(p.isCover=1,p.picture_id,NULL)) AS pictureId
FROM `PICTURES` p
GROUP
BY p.album
注意:MySQL IF()
函数可以替换为更可移植的 ANSI 标准等效函数
, MAX(CASE WHEN p.isCover = 1 THEN p.picture_id ELSE NULL END) AS pictureId
注意:建议使用小写字母作为表名称。
... it is best to adopt a consistent convention, such as always creating and referring to databases and tables using lowercase names. This convention is recommended for maximum portability and ease of use.
https://dev.mysql.com/doc/refman/5.7/en/identifier-case-sensitivity.html
关于mysql - SQL查询统计图片数量并获取封面图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50606422/