开发者

MySQL: Returning a count of objects matching all tags

开发者 https://www.devze.com 2023-03-04 12:04 出处:网络
I have a situation where I need to match an objects to multiple tags simultaneously so that results set is \"narrowed down\" to match all tags. I\'ve found the following MySQL query for this:

I have a situation where I need to match an objects to multiple tags simultaneously so that results set is "narrowed down" to match all tags. I've found the following MySQL query for this:

  SELECT * 
    FROM OBJECTS o
    JOIN OBJECTSTAGS ot ON ot.object_id = o.id
    JOIN TAGS t ON t.id = ot.tag_id
   WHERE t.name IN ('tag1','tag2')
GROUP BY o.id
  HAVING COUNT(DISTINCT t.name) = 2

... where 2 is the number of tags being matched. It works fine.

开发者_如何学PythonHowever, I need the query to return a count of the objects instead of the objects themselves. This query seems to confuse itself if I add COUNT(*) to the SELECT. I'm hesitant to return just the ids for example and do a PHP count of them because they could add up to a very large number. I would therefore like MySQL to return the count.

Could anyone suggest a good way to do this? Breaking it into two queries would be acceptable.

Thanks in advance.


Use:

  SELECT COUNT(o.*) AS numObjects
    FROM OBJECTS o
   WHERE EXISTS (SELECT NULL
                   FROM OBJECTSTAGS ot 
                   JOIN TAGS t ON t.id = ot.tag_id
                              AND t.name IN ('tag1','tag2')
                  WHERE ot.object_id = o.id)
0

精彩评论

暂无评论...
验证码 换一张
取 消