Hello all i have a table which have two columns trial_id
, category_id
I am attaching the image so that it become more clear.
When I want the records of trial_id
which have category_id
i can run a query like
SELECT * FROM `trial_category` WHERE category_id IN ( 259, 260 )
You can se it give trial_id
associate with these two category_id
My problem is that now I want the trial_id
which have exact match with these two category_id
how can i do?
Means if you notic only trial_id
73 have both 259 and 260 category_id
then my result should be only 73.
Thanks
SELECT trial_id, count(trial_id) AS ccnt
FROM trial_category
WHERE category_id IN ( 259,260)
GROUP BY trial_id
HAVING ccnt = 2
Use group by clause:
SELECT trail_id FROM `trial_category`
WHERE category_id IN ( 259, 260 )
GROUP BY trial_id
HAVING count(trial_id) = 2
This is an example of a "set-within-sets" subquery. Here is a solution using group by
with the having
clause:
SELECT trial_id
FROM trial_category
group by trial_id
having sum(case when category_id = 259 then 1 else 0 end) > 0 and
sum(case when category_id = 260 then 1 else 0 end) > 0;
Each condition in the having
clause is satisfied when one of the rows has the specific category. You can see how this easily generalizes to more categories. Or even to the case 259 but not 260 and 261.
If you want exactly these two categories, you can filter on rows that do not have any other categories by adding this clause:
sum(case when category_id not in (259, 260) then 1 else 0 end) = 0;
IN ( 259, 260 )
You need to use GROUP BY
for trial_id
SELECT q.* FROM (
SELECT *,COUNT(trial_id) as tcount FROM trial_category
WHERE category_id IN ( 259, 260 ) GRUOP BY trial_id ) q
WHERE q.tcount >1
OR
SELECT *,COUNT(trial_id) as tcount FROM trial_category
WHERE category_id IN ( 259, 260 ) GRUOP BY trial_id HAVING tcount >1
尝试这个
SELECT DISTINCT trail_id FROM `trail_category` WHERE category_id IN ( 259, 260 );
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.