skip to Main Content

I’ve a MySql table which contains rows like,

pid country
436 1
436 5
436 7
439 7
440 3
446 7
446 1

For Example, I am trying to retrieve products which has only country 7 and should not present in other combination. How can I achieve this?

I tried like below:

SELECT * from table_name WHERE country = 7;

but outcome/result contains pid 436,439 and 336. It should only give 439.

2

Answers


  1. You can use not exists for this:

    select *
    from table_name t 
    where t.country = 7
    and not exists (
      select * from table_name t2
      where t2.pid = t.pid and t2.pid != t.pid
    );
    
    Login or Signup to reply.
  2. We can use aggregation here:

    SELECT pid
    FROM yourTable
    GROUP BY pid
    HAVING SUM(country <> 7) = 0;
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search