开发者

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 org开发者_运维百科anised them. 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".


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:

 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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜