Debopam Mitra
Debopam Mitra

Reputation: 1870

Select rows with categoryId belongs to 2 or more values

I have a table like this :

enter image description here

I want to find the courseId where the courseId belongs to 2 or more categoryIds. E.g. If I give the categoryId to be 18112 and 21115 then it should only give the courseIds - 18602 & 21101.

How can I do that?

Upvotes: 0

Views: 49

Answers (4)

Reyan Chougle
Reyan Chougle

Reputation: 5311

You can use GROUP BY and HAVING as below:

SELECT courseId
FROM table_name
WHERE categoryId IN (18112,21115)
GROUP BY courseId
HAVING COUNT(DISTINCT categoryId) >= 2

Upvotes: 1

Gilad Green
Gilad Green

Reputation: 37299

select courseId 
from courses_categories
where categoryId in (18112,21115)
group by courseId
having count(distinct categoryId) >= 2

Upvotes: 1

Sankar
Sankar

Reputation: 7107

Group by and Having clauses will helps you.

select courseId
from your_table
where categoryId in (18112,21115)
group by courseId
having count(distinct categoryId) >= 2

Upvotes: 1

juergen d
juergen d

Reputation: 204746

Group by the courseId and select only those having these 2 categoryIds

select courseId
from your_table
where categoryId in (18112,21115)
group by courseId
having count(distinct categoryId) = 2

Upvotes: 1

Related Questions