简体   繁体   English

将两个(或更多)SQL 结果与 PHP 动态组合?

[英]Combining two (or more) SQL results dynamically with PHP?

I've gone through several similar questions, none seem to deal with this type of problem.我已经经历了几个类似的问题,似乎都没有处理这类问题。

I want to select all posts from people who are friends, and then organised them.我想 select 所有朋友的帖子,然后整理它们。 All my approaches I tried so far have done it friend-by-friend, which is annoying since it doesn't show you newest posts at the top.到目前为止,我尝试的所有方法都是逐个朋友完成的,这很烦人,因为它没有在顶部显示最新的帖子。

Here's how my database is structured, I left out any irrelevant details:这是我的数据库的结构,我省略了任何不相关的细节:

Users table:用户表:

 UId (Unique UserId)

Friend table:好友表:

 Person1 | Person2

Posts table:帖子表:

 PostId | AuthorId | Text | DatePosted

AuthorId, Person1 and Person2 all link to a user via their "UId". AuthorId、Person1 和 Person2 都通过他们的“UId”链接到用户。

Without knowing how you've structured your database, this is a tough question to answer.在不知道如何构建数据库的情况下,这是一个很难回答的问题。

In the past, I've done something like this (single query), but my databases were structured pretty well specifically for this purpose.过去,我做过类似的事情(单个查询),但我的数据库结构非常好,专门用于此目的。

 SELECT * from posts
 LEFT JOIN users ON (poster_id=user_id)
 WHERE poster_id IN (
     SELECT related_id
     FROM user_relationships
     WHERE user_relationship = 'friend'
     AND user_id = 1
 )
 ORDER BY post_date DESC
 LIMIT 20   

Added - Not in front of MySQL right now, but for the DB specified by OP, it may look more like this:补充 - 现在不在 MySQL 前面,但是对于 OP 指定的 DB,它可能看起来更像这样:

 SELECT * from posts
 LEFT JOIN users ON (poster_id=user_id)
 WHERE poster_id IN (
     SELECT (if(user_idA='.$userId.'), user_idB, user_idA) as related_id,
     FROM user_relationships
     WHERE accepted = TRUE
     AND '.$userId.' IN (user_idA, user_idB)
 )
 ORDER BY post_date DESC
 LIMIT 20   

Something like that will work:像这样的东西会起作用:

SELECT p.*
FROM Posts p
  JOIN FriendRequests fr
    ON fr.from = p.authorid
WHERE fr.accepted = 1
  AND fr.to =  @myid
ORDER BY p.postdate DESC

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

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