简体   繁体   English

无法解决复杂的SQL查询

[英]Can't figure it out a complex SQL query

I need to do a query between these 3 tables : members, messages and schools. 我需要在这3个表之间进行查询:成员,消息和学校。

In my table "messages", I save the member ID (to know who wrote the message). 在我的“邮件”表中,保存成员ID(以了解谁写了邮件)。 In my table "members", I save the school ID of the member. 在我的“成员”表中,保存该成员的学校ID。

But I would like to create something like a Facebook wall, where you could see a list of all the messages from anyone who's in your school. 但是我想创建一个类似Facebook墙的东西,您可以在其中看到来自您学校中任何人的所有消息的列表。

It's easy for me to get all the posts from anybody, but I can't figure out how to get only the posts from people in your school. 我很容易从任何人那里获得所有帖子,但我不知道如何仅从您学校的人那里获得帖子。 I save the school ID of the member in a session so it's easy to know from which school we need to get the posts. 我在会议中保存了该成员的学校ID,因此很容易知道我们需要从哪个学校获得职位。

Is it possible to do this in one query? 是否可以在一个查询中执行此操作?

Thanks ! 谢谢 !

Here is the SQL query: 这是SQL查询:

SELECT     msg.*
FROM       messages AS msg
INNER JOIN members AS mem ON msg.member_id = mem.id
INNER JOIN schools AS sch ON mem.school_id = sch.id
WHERE      sch.id = ?

As Michael suggested in the comments, here is an article that explains SQL joins visually: http://www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins 正如Michael在评论中建议的那样,这是一篇以可视化方式解释SQL连接的文章: http : //www.codeproject.com/Articles/33052/Visual-Representation-of-SQL-Joins

SELECT m.message 
FROM messages m
JOIN members b
ON m.memberid = b.memberid
JOIN schools s
ON s.schoolid = b.schoolid
WHERE s.schoolid = "replace by the schoolid stored in session"

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

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