1

如何使用 COUNT 获取与 LIKE 查询匹配的所有记录的计数?

我有一个表keywords定义为

+------+-------+-----------------+
| id   | photo | keyword         |
+------+-------+-----------------+
| 3504 |   664 | 2013            |
| 3505 |   664 | bl elfring      |
| 3506 |   664 | indoor track    |
| 3507 |   664 | people          |
| 3508 |   664 | 1-5_it_0128.jpg |
+------+-------+-----------------+

photo部分定义为

+-----+-------------------+-------------+--------------+------------+
| ID  | name              | photo_width | photo_height | date_taken |
+-----+-------------------+-------------+--------------+------------+
| 760 | 12-8_mbb_0072.jpg |         425 |          600 | 2012-12-08 |
| 759 | 12-8_mbb_0071.jpg |         459 |          600 | 2012-12-08 |
| 758 | 12-8_mbb_0069.jpg |         457 |          600 | 2012-12-08 |
| 757 | 12-8_mbb_0057.jpg |         395 |          600 | 2012-12-08 |
| 756 | 12-8_mbb_0050.jpg |         800 |          468 | 2012-12-08 |
+-----+-------------------+-------------+--------------+------------+

keywords.photo引用 photos.ID 并且keywords.keyword是与该图像关联的 IPTC 关键字。

我想计算与特定关键字相关的所有图像

至今,

SELECT COUNT(keywords.photo) AS keyword_count, keywords.keyword 
FROM keywords INNER JOIN photos ON keywords.photo = photos.ID
WHERE keywords.keyword LIKE '%nic%'

返回

+---------------+-------------+
| keyword_count | keyword     |
+---------------+-------------+
|            31 | nicole **** |
+---------------+-------------+

然而,

SELECT DISTINCT keyword
FROM keywords
WHERE keyword LIKE '%nic%'

返回

+----------------+
| keyword        |
+----------------+
| nicole ****    |
| nicole ******* |
| bonny **nic*   |
| nicole ******  |
+----------------+

如何获得包含第二个查询结果的计数字段?

4

2 回答 2

3

如果我理解正确,您想要与给定关键字匹配的照片数量?如果是这种情况,您可以使用该GROUP BY子句:

SELECT
    COUNT(keywords.photo) AS keyword_count, keywords.keyword 
FROM
    keywords INNER JOIN photos ON keywords.photo = photos.ID
WHERE
    keywords.keyword LIKE '%nic%'
GROUP BY
    keywords.keyword

这将按keywords.keyword列对结果进行分组,并计算每个结果的使用次数。请注意,以这种方式匹配/分组的“关键字”是唯一的 - 它不会按部分匹配分组(即"bonny **nic*不同于nicole ******)。

于 2013-01-08T18:06:34.277 回答
2

您想按唯一关键字分组:

SELECT COUNT(keywords.photo) AS keyword_count, keywords.keyword 
FROM keywords INNER JOIN photos ON keywords.photo = photos.ID
WHERE keywords.keyword LIKE '%nic%'
GROUP BY keywords.keyword
于 2013-01-08T18:05:59.377 回答