简体   繁体   English

通过外键连接的另一个表的参考数据

[英]Reference data from another table, connected by a foreign key

I'm building a social site in which each user belongs to a particular group. 我正在建立一个社交网站,其中每个用户都属于一个特定的组。 The home page (the "news feed", so to speak) displays recent posts from anyone within their group. 主页(可以说是“新闻提要”)显示了该组中任何人的最新帖子。 Therefore, I need to grab any stories from people that match the group ID of the logged-in user. 因此,我需要从与已登录用户的组ID匹配的用户那里获取所有故事。

The stories table contains several columns, one of which is poster_id (which is FK constrained to the ID column in the users table), and the user table also has a column group_id. 故事表包含几列,其中一列是poster_id(FK约束到users表中的ID列),user表中还有一列group_id。 Essentially, what I need to do is this: 本质上,我需要做的是:

SELECT * FROM stories WHERE poster_id.group_id = '$logged_in_user_group'

But obviously I can't just directly reference group_id by going through poster_id. 但是显然,我不能仅通过poster_id直接引用group_id。 What would be the simplest way to kind of "backtrack" into the users table, so I can compare the group_id? 将“回溯”到users表中的最简单方法是什么,以便可以比较group_id?

You are looking for a "join": 您正在寻找“加入”:

select stories.*
from stories
join poster on poster.poster_id = stories.poster_id
where poster.group_id = '$logged_in_user_group'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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