简体   繁体   中英

Is there any way to do this with a single query?

I've got these tables:

home_table
----------
home_id | home_name

user_table
---------
user_id | user_name

user_home_rel_table
----------
id | user_id | home_id

(Many users may belong to many homes)

I have an api call called /homes/2/users which i want to return all the users of the home with id 2.

Along with the call, is the user id of the current user.

If the user belongs to the home (in this case id 2), then he is allowed to see the other users. The user belongs to the home if he exists in user_home_rel_table as such:

user_home_rel_table
----------
id | user_id    | home_id
----------------------
1  | $currentID | 2

I believe that this will give you what you are looking for. I put in $currentid and $home_id as placeholders for your parameters. I also used slightly different names for the tables since I refuse to use table names with _table appended on the end... ;)

SELECT
    U.user_id,
    U.user_name
FROM
    User_Homes UH
INNER JOIN User_Homes UH2 ON UH2.home_id = UH.home_id
INNER JOIN Users U ON U.user_id = UH2.user_id
WHERE
    UH.user_id = $currentid AND
    UH.home_id = $home_id  -- 2

This will only return results if the $desiredUserID is part of the home requested with $desiredHomeID :

SELECT u.user_id, u.user_name
FROM home_table h
LEFT JOIN user_home_rel_table uh ON (uh.home_id = h.home_id)
LEFT JOIN user_table u ON (uh.user_id = u.user_id)
LEFT JOIN user_home_rel_table up ON (uh.home_id = up.home_id AND up.user_id = $desiredUserID)
WHERE h.home_id = $desiredHomeID AND up.user_id IS NOT NULL

I am just going to use Tom H's version (projection and OBJECT names) to present an alternative way

SELECT
    U.user_id,
    U.user_name
FROM
   User_Homes UH2 
   INNER JOIN Users U ON U.user_id = UH2.user_id
WHERE
    UH2.home_id = $home_id  -- 2
    AND EXISTS (SELECT 1 FROM User_Homes WHERE 
          user_id = $currentid AND home_id = $home_id)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM