SELECT COUNT FROM SELECT DISTINCT cd cid as id cmp name FROM cities JO

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
SELECT
*,COUNT(*)
FROM
(
SELECT
DISTINCT cd.cid as id, cmp.`name`
FROM
cities c
JOIN districts d ON (d.cid = c.id)
JOIN city_delivery cd on (cd.district = d.id)
JOIN companies cmp ON (cmp.id = cd.cid)
WHERE
c.id IN (9)
) cm
JOIN comp_tags t ON (t.cid = cm.id)
WHERE
t.tid IN (17,18,19)
GROUP BY t.cid
HAVING
COUNT(t.tid) = 3