Mysql – Finding Records that Have Same Options

MySQLrelational-division

Trying to figure out how find out which user records have at least 1 similar option enabled and then display these.

Tables:

user (id, username)
thing (id,title)
uthing (id, uid, tid)

Uthing table has a record of what options each user have selected.

uid = user.id
tid = thing.id

I need to compare the options (uthing) from user id 1 with all other users.

How can find users that have 1 or more options(uthing) of USER ID 1 and return these users with the options found?

This query will give me all options for user id 1.

select thing.title,thing.id as thingid 
from thing join uthing on uthing.tid = thing.id where uthing.uid = 1;

Best Answer

You achieve this by following this query

select uthing.id, uthing.uid, thing.title
from uthing left join thing on uthing.tid = thing.id
where uthing.tid in (
        select thing.id
        from thing join uthing on uthing.tid = thing.id
        where uthing.uid = 1
     );