简体   繁体   中英

SQL - query for searching data in both table at the same time?

Suppose I have a table called UserFollows , where I keep Follow relationships;

UserId FollowedId

Then I have a general Users table and it is like;

Id Username

I use a query like the following when I want to get all followers of a user with ID 100 ;

SELECT*FROM UserFollows WHERE FollowedId = 100;

And suppose that I also want to query the following case;

I want to search among the followers of a particular user, with a specific Username.

So, It should be like GET ME ALL OF THE USERS THAT HAS THE WORD 'hey' IN THEIR USERNAMES AMONG THOSE FOLLOWING ME

If I had Username in my UserFollows table, I'd easily write it like;

SELECT*FROM UserFollows WHERE FollowedId = 100 AND Username LIKE '%a';

But I don't keep their Usernames in UserFollows

You need to include the Users table in the query.

SELECT uf.*
FROM UserFollows uf
  inner join Users u on u.Id = uf.UserId
WHERE uf.FollowedId = 100 
  AND u.Username LIKE '%a';

or, more clearly

SELECT uf.*
FROM UserFollows uf
  inner join Users follower on follower.Id = uf.UserId
  inner join Users followed on followed.Id = uf.FollowedId
WHERE followed.UserName = 'ME'
  AND follower.Username LIKE '%a';

Although "followed" may be a keyword, so you would need different aliases or you would need to handle the names appropriately.

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