1

I have table 'devices' with following structure.

id | user_id | device

1 | 12 | tablet
2 | 12 | pc
2 | 12 | mobile

This table is related many to one with table "users". One user can have multiple devices, and I would like to select only users that has two devices "tablet" and "pc" for example.

How can I do it.

Thank you

4
  • Do you have only 3 distinct devices? Commented Dec 16, 2021 at 4:32
  • 1
    Not only 3 can by much more. Commented Dec 16, 2021 at 4:51
  • The answer I have suggested will handle this case. Commented Dec 16, 2021 at 4:52
  • I wonder fi will not be better to aggregate colum device to string and in second query search by "like". What do you think? Commented Dec 16, 2021 at 5:04

2 Answers 2

1

try this one

select user_id
from devices
group by user_id 
having count(*) = 2 and max(device) = 'tablet' and min(device) = 'pc'

demo

Sign up to request clarification or add additional context in comments.

Comments

0

You can use multiple sub-queries to achieve this:

SELECT DISTINCT user_id
FROM devices
WHERE user_id NOT IN 
      (
      SELECT DISTINCT user_id
      FROM devices
      WHERE device IN
          (
          SELECT DISTINCT device
          FROM devices
          WHERE device NOT IN ('tablet', 'pc')
          )
      )
AND user_id IN
      (
      SELECT t.user_id
      FROM devices AS t
      INNER JOIN (SELECT user_id FROM devices WHERE device='pc') AS p
      ON t.user_id=p.user_id
      WHERE device='tablet'
      )

This is not an optimized query. We can use JOINS instead of WHERE to make it faster

Demo here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.