开发者

MySQL query to list common values between 2 users

This table lists events and users that are attending the event :

User&n开发者_Python百科bsp;        Event

 Joe            Movie

 Joe            Mall

 Jill              Mall

 Joe            Drinking

 Jenn          Drinking

 Jill              Drinking

How can I run a query on this table to list all the events that are common between 2 given users.

My guess is, this will need a self join, but I'm not sure.


SELECT *
FROM myTable joe
JOIN myTable jill ON jill.User='Jill' AND jill.Event=joe.Event
WHERE joe.User='Joe'

This might work also. It can sometimes be more efficient doing it this way (putting all conditions in the JOIN)

SELECT *
FROM myTable joe
JOIN myTable jill ON jill.User='Jill'
    AND jill.Event=joe.Event
    AND joe.User='Joe'


SELECT * 
   FROM myTable t1
      JOIN myTable t2 
         ON t1.event = t2.event
       and t2.User="Jill"
   where
      t1.user = "Joe"


select event from table group by event having count(user) =2

that won't give you the names of the users though


select eventname from user_event JOIN user_event as t2 USING (eventname) 
where user_event.username="joe" and t2.username="jill"

Here, 'user_event' is the name of your table and table 't2' is the alias of the 'user_event" table

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜