简体   繁体   中英

How can i combine data from two mysql queries

I asked this question earlier but no one seemed to give me the answer i looking for so i have.

So How can i combine data from two mysql queries where i get every column or how can i combine two mysql queries where i get every column that i specified in the two queries?

QUERY 1:

SELECT b.id, b.post_text, c.default_photo, d.first_name, e.status 
FROM posts b 
INNER JOIN profiles c 
INNER JOIN users d 
INNER JOIN friendship e 
ON b.from_user = c.user_id 
AND b.from_user = d.id 
AND e.friend_id = b.from_user 
WHERE e.status = 'Friend' 
AND e.user_id = :id
ORDER BY b.id DESC

QUERY 1 Returns posts. Posts that friends posted

QUERY 2

SELECT b.id, b.by_who_id, b.photo_dir, c.default_photo, d.first_name, e.status
FROM photos b 
INNER JOIN profiles c 
INNER JOIN users d 
INNER JOIN follower e 
ON b.by_who_id = c.user_id 
AND b.by_who_id = d.id 
AND e.from_user = b.from_user 
WHERE e.status = 'Following' 
AND e.following_who_id = :id
ORDER BY b.id DESC

now QUERY 2 returns photos . if say i follow "someone" it fetches their photos

now what i want is to view a combination of posts from friends and photos from people i follow .. how can i do this oh and im going to ORDER BY DATE by the way SO it can return

photo 
photo 
post 
post 
post 
photo 
post 

no the way i might output this if its 1 query might be like

<?php
if ( !empty($two_queries_in_one) ) {
    foreach($two_queries_in_one as $post) :
        if ( empty($post["photo_dir"]) ) {
?>
            html here
<?php
    } else {?>
            html here

<?php } endforeach;

}
?>

The code can use a bit optimalisation but the idea is clear:

$combined = array();
foreach($query1 as $row)
{
    $combined[$row['timestamp']][] = $row; // unix timestamp in order to sort
}

foreach($query2 as $row)
{
    $combined[$row['timestamp']][] = $row; // unix timestamp in order to sort
}

ksort($combined); // sort the keys

foreach($combined as $timestamp => $rows)
{
   foreach($rows as $row)
   {
      if(isset($row['photo_dir'])
      {
         // your code for the photo 
      }
      else
      {
         // your code for the normal post
      }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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