I have Mysql table with 3 columns: id, company_id and tag_id. It's used to link companies and tags together. Table schema:
CREATE TABLE tbl_company_tag_link (
id BIGINT NOT NULL AUTO_INCREMENT,
company_id BIGINT NOT NULL,
tag_id BIGINT NOT NULL,
PRIMARY KEY(id)
);
Any company can be linked with any number of tags. I need to select companies, that have ALL of the specified tags attached. For example, I need company_id that have tag_id = 1,2,3 (all of them!) The query that I came to is ugly:
SELECT company_id, GROUP_CONCAT(tag_id) as group_concat_tag_id
FROM tbl_company_tag_link
WHERE tag_id IN (1,2,3)
GROUP BY company_id
HAVING group_concat_tag_id = "1,2,3"
I need help with writing query, that would be fast.
I've created sqlfiddle with my schema and query for fast testing: http://sqlfiddle.com/#!9/2416f/2
too late, found the same question with detailed answers: Need help with sql query to find things tagged with all specified tags