SELECT companies id companies name IF franchise id franchise id as fra

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
SELECT
companies.id,
companies.name,
IF (franchise.id > 0, franchise.id, 0) as franchise,
COUNT(DISTINCT comp_tags.tid) as q
FROM
cities,
city_delivery,
districts,
companies LEFT JOIN franchise ON (
companies.parent = franchise.id
),
comp_tags
WHERE
cities.id IN (10)
AND
cities.id = districts.cid
AND
districts.id = city_delivery.district
AND
city_delivery.cid = companies.id
AND
companies.id = comp_tags.cid
AND
comp_tags.tid IN (16,17)
GROUP BY
IF (franchise.id > 0, companies.name, companies.id)
HAVING
IF (0, q = 2, 1)