I have the following table called Stores:
Name | Country | Category
Pharmacy Japan Health
Green Vine Italy Dining
You can use EXISTS
:
SELECT t.*
FROM table t
WHERE EXISTS (SELECT 1
FROM table t1
WHERE t1.Country = t.Country AND
t1.category = t.category AND
t1.Name <> t.Name
);
You can use following query to get all such categories for which all countries are same:
Select t.category
From table t
Group by t.category
Having count(distinct country)=1
Then you can use it to get StoreNames:
Select t.name
From table t
Where t.category in
( Select t.category
From table t
Group by t.category
Having count(distinct country)=1)
This syntax is compatible to MS sql server, but I hope logic can be translated to mysql.
You can use aggregation with a HAVING
clause, that checks that the minimum country is the same as the maximum country for a category, i.e. all countries are the same (if there cannot be NULL
s, which seems to be the case). Then inner join these categories.
SELECT *
FROM elbat t1
INNER JOIN (SELECT t2.category
FROM elbat t2
GROUP BY t2.category
HAVING max(t2.country) = min(t2.country)) x
ON x.category = t1.category;