简体   繁体   中英

MySQL Query from multiple tables

I have 3 MySQL Tables in my DB. They are:

  • Users - User_ID, firstName, lastName, email and Password
  • Activity - Activity_ID, UserID, Date, Time, Activity
  • Follow - Follow_ID, UserID, FollowID

I want to be able to generate an output (to XML, but I've already done that), that will put out activity for users that a set user follows.

For Example: User 1 follows User 2,3 and 5 but not user four. So for that user only show Activity from user 2,3 and 5. But for another user that follows users 3 and 4, show only 3 and 4.

I'm a bit of a novice when it comes to SQL/MySQL, so I'm a bit lost.

Look into using joins, this will be what you want to use. I would also re-evaluate your table structures, I think there is flawed logic in your table structure...

Something like this as an example (not correct, but to give you an idea):

select * from dbo.Users as usr
join dbo.follow as flw on usr.userId = flw.usrId
join dbo.Activity as act on act.UserId - flw.userID

Here is an example structure of DB: 在此处输入图片说明

By using the above structure.

Every time a user follows another user, a record is added to the Follow table. This is a one to many relationship. User * Follows.

You can now query something like:

select followId from dbo.Follow as flw where flw.UserId = 123

This would return a reference to all of the users a user is following.

You could then join the UserFollow table to identify the relationship of each follow record (basically matching user a > user b).

I dunno if this makes sense. Sort of hard to explain without... Does this make sense?

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