How can I get a count of all records that match a LIKE query using COUNT?
I have a table keywords defined as
+------+-------+-----------------+
| id | photo | keyword |
+------+-------+-----------------+
| 3504 | 664 | 2013 |
| 3505 | 664 | bl elfring |
| 3506 | 664 | indoor track |
| 3507 | 664 | people |
| 3508 | 664 | 1-5_it_0128.jpg |
+------+-------+-----------------+
and photo defined in part as
+-----+-------------------+-------------+--------------+------------+
| 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 references photos.ID and keywords.keyword is an IPTC keyword associated with that image.
I’d like to get a count of all images associated with a particular keyword
So far,
SELECT COUNT(keywords.photo) AS keyword_count, keywords.keyword
FROM keywords INNER JOIN photos ON keywords.photo = photos.ID
WHERE keywords.keyword LIKE '%nic%'
returns
+---------------+-------------+
| keyword_count | keyword |
+---------------+-------------+
| 31 | nicole **** |
+---------------+-------------+
However,
SELECT DISTINCT keyword
FROM keywords
WHERE keyword LIKE '%nic%'
returns
+----------------+
| keyword |
+----------------+
| nicole **** |
| nicole ******* |
| bonny **nic* |
| nicole ****** |
+----------------+
How can I get a count field with the results of the second query?
If I understand correctly, you want the number of photos that match a given keyword? If this is the case, you can use the
GROUP BYclause:This will group the results by the
keywords.keywordcolumn with a total count of how-many times each one is used. Please note that the “keywords” that are matched/grouped this way are unique – it will not group by partial matches (i.e."bonny **nic*is different thannicole ******).