一次从数据库中查询两个表?
我试图同时查询两个表以在“新闻源”中显示成员的活动。
所以,我有两个查询,但我想将它们组合起来:
$status_query = mysql_query("SELECT * FROM member_status_updates WHERE member_id = '1'"):
and
$topic_query = mysql_query("SELECT * FROM topics WHERE author_id = '1'");
如何组合这两个查询,以便在插入它们时按顺序显示它们?如果状态是 5 秒前发布的,并且主题是昨天发布的,那么状态更新应该位于顶部。为此,我想我需要结合这两个查询。
但我的另一个担忧是,如果我按 ID DESC
对它们进行排序,会不会弄乱显示?例如:如果 1 秒前发布的状态更新的 ID 为 50,昨天发布的主题的 ID 为 100,则该主题是否会首先显示,因为该 ID 大于状态更新的 ID,即使状态更新发布于 1 秒前?如果是这样,那么我想知道如何按日期对它们进行排序,每条记录都有一个时间戳。
非常感谢任何帮助。
I am trying to query two tables at once to show member's activity in a "newsfeed".
So, I have my two queries but I would like to combine them:
$status_query = mysql_query("SELECT * FROM member_status_updates WHERE member_id = '1'"):
and
$topic_query = mysql_query("SELECT * FROM topics WHERE author_id = '1'");
How can I combine these two queries so I can show them in order by the time they were inserted? If a status was posted 5 seconds ago and a topic was posted yesterday, then the status update should be on top. To do this, I figured I would need to combine the two queries.
But my other concern is if I sort them by the ID DESC
would that mess up the display? For example: If a status update that was posted 1 second ago had an ID of 50 and a topic posted yesterday had an ID of 100, would the topic show up first because the ID is greater then the status update's ID even though the status update was posted 1 second ago? If so, then I was wondering how I could sort them by the date, I have a timestamp for each record.
Any help is greatly appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一种解决方案是使用 Union All 查询:
问题是两个查询的列数和数据类型必须相同。 (避免选择 * 的另一个原因)。
如果您知道总是会从
topics
表中获取一行,并且考虑到topics.author_id
映射到member_status_updates.member_id
,您可以使用左连接。如果您还希望最后一行基于某个时间戳值,您可以执行以下操作:One solution is to use a Union All query:
The catch is that the column count and data type of the columns of the two queries must be identical. (Another reason to avoid Select *).
If you knew you would always get a row from the
topics
table and given thattopics.author_id
maps tomember_status_updates.member_id
, you could use a Left Join. If you also want the last row based on some timestamp value, you could do something like: