mysql - Check if user and another user like each other and fetch the liking user's information -
this first question here, although i've been utilizing site years help. maybe it's because i'm sick can't figure out.
i have 2 tables in database [user] , [like]
the [user] table has basic information (id, name, age)...
the [like] table stores users user (user, user) ... example if user a likes user b, stores in [like] table user (a) likes user(b). foreign key constraints.
i need fetch database, users user a, user a likes back, including respective data [user] table.
example...
[like table] user -> user b user b -> user user -> user c user c -> user b assuming current user i'm checking user a, need query return
(user b, user b's name, user b's age) because both user a , user b each other , thus, need info user b only.
my current mysql statement goes:
select li.like_id `like` li join `like` ui on li.like_id = ui.user_id li.user_id = **user_a** group li.like_id; which seemingly returns people user_a... can't figure out why because i've mentioned earlier, i'm out of it... must work... work shall... help. thanks.
select u.* `like` ul inner join `like` lu on ul.user_id = lu.like_id , ul.like_id = lu.user_id inner join `user` u on u.id = ul.like_id ul.user_id = ? explanation key in join between 2 instances of table. says match each "like" "like" has same user_id , like_id values except in reverse order. using inner join rather outer join guarantees relationship reciprocal throws away ones aren't interested in.
at point you're interested in "liked" user's attributes final step ul.like_id against user table. (lu.user_id has have same value work too.)
notevenwrong's answer pretty identical. have disadvantage of using user_a parameter in 2 places although eliminated in subquery correlating outer reference.
i think join kind of highlight symmetrical nature of query , more adaptable other uses. it's possible exists version faster though.
Comments
Post a Comment