在查询中包含COUNT

时间:2013-01-08 18:03:33

标签: mysql

如何使用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引用了照片.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 ******  |
+----------------+

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

2 个答案:

答案 0 :(得分: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 ******不同。)

答案 1 :(得分: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