简体   繁体   中英

SQL Query Multiple Conditions

I have two tables like these. They represent an interaction of following/followers between two users.

users
---------------------------------------
id    | username | <br>
1     | bobby    | <br>
2     | jessica  | <br>
3     | jonny    | <br>
4     | mike     | <br>


follows
----------------------------------------
id    | userid_1 | userid_2 | <br>
1     |  1       |    2     | <br>
2     |  3       |    4     | <br>
3     |  4       |    1     | <br>

Set my user id to 1 for example, I want a query that returns something like this

-----------------------------------------
 username | userid_1 | userid_2 |<br>
 jessica  | 1        |  2       |<br>
 mike     | 4        |  1       |<br>

Any help to solve this problem? :)

This is a bit more complicated than it first seems, because you want the name of the other user:

select u.username, f.*
from follows f join
     users u
     on (u.id = f.userid_1 and f.userid_2 = 1) or
        (u.id = f.userid_2 and f.userid_1 = 1)
where 1 in (f.userid_1, f.userid_2);

Actually, the where clause is not needed (it is covered by the on ). I think it clarifies the filtering however.

You can JOIN tables in following:

SELECT u.username, f.userid_1, f.userid_2
FROM users u
JOIN follows f
ON u.Id = f.Id
Select username, userid_1, userid_2
from users, follows 
where users.id = follows.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