Question

I have 3 tables:

  • Places
  • Users
  • User_Likes_Place

Places has information about places (id, address, number, name, bla bla) Users has information about users (id, name, age, bla bla) User_Likes_Place is the relation between Places and Users and has 3 columns: id, id_place, id_user.

I need the list of all the places, and I also need to know which places the user likes. I'm trying to do a query to select all the places, adding a column that indicates if that place is liked from a specific user, so in the query I will filter by user.id.

The result should be something like this:

place.id, place.name, place.address, place...., USER_LIKES_THIS_PLACE
001, name001, addr001, blabla, 1 (or Y/N, I don't know..)
002, name002, addr002, blabla, 0
003, name003, addr003, blabla, 0
004, name004, addr004, blabla, 1
005, name005, addr005, blabla, 1

Do you have any suggestion? Thank you all.

Was it helpful?

Solution

Here is one way to do this:

select p.*,
       (case when ulp.id_user is not null then 'Y' else 'N' end) as UserLikesPlace
from places p left outer join
     user_like_places ulp
     on p.id = ulp.id_place and
        ulp.id_user = @IDUSER;

It makes the assumption that there are no duplicates in user_like_places. If that is possible, then you need a distinct or group by to remove the duplicates.

The left outer join keeps all the information about all the places. It then joins in the assocation table. If there is a match, then ulp.id_user is not null and the user likes the place. Otherwise, it is NULL and the user does not. If you just want 0 or 1, you can replace the case statement with ulp.id_user is not null.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top