简体   繁体   中英

List users from two joined tables with mySQL

I've these two tables:

___Hotels

|-------------|------------|
| HOT_HotelId | HOT_Name   |
|-------------|------------|
|           1 |    Hotel A |
|           2 |    Hotel B |
|-------------|------------|

___UsersHotelsLink

|--------|------------|-------------|
| UHL_Id | UHL_UserId | UHL_HotelId |
|--------|------------|-------------|
|      1 |          1 |             |
|      2 |        131 |           1 |
|      3 |        131 |           2 |
|--------|------------|-------------|

I would like to list hotels from ___Hotels for user in ___UsersHotelsLink .

So, I'm using this working query:

SELECT * 
FROM ___UsersHotelsLink
LEFT JOIN ___Hotels 
    ON ___UsersHotelsLink.UHL_HotelId = ___Hotels.HOT_HotelId
WHERE HOT_Status != "inactive"
    AND UHL_Status != "inactive"
    AND UHL_UserId = 131
ORDER BY HOT_Creationdate ASC

This working when the user (131) has a hotel into ___Hotels table. But if I replace 131 by 1 (witch is the super admin), it doesn't work. It doesn't return any row.

I would like to have one row return.

What I making wrong please ?

Thanks a lot.

I assume you mean you want a row to be returned when searching by a user without a hotelid . Assuming so, your where criteria is negating the outer join and thus causing no rows to be returned. Move it to the on condition and it should return the user with null hotel data:

SELECT * 
FROM ___UsersHotelsLink
LEFT JOIN ___Hotels 
    ON ___UsersHotelsLink.UHL_HotelId = ___Hotels.HOT_HotelId 
        AND HOT_Status != "inactive"
WHERE UHL_Status != "inactive"
    AND UHL_UserId = 131
ORDER BY HOT_Creationdate ASC

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