如何组合来自两个mysql查询的数据

时间:2014-07-23 08:50:04

标签: php mysql

我之前问过这个问题,但似乎没有人给我答案,所以我有。

  

那么如何组合来自两个mysql查询的数据呢?   专栏或如何结合两个mysql查询,我得到的每一个   我在两个查询中指定的列?

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返回帖子。朋友发布的帖子

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

现在QUERY 2返回照片。如果说我跟随“某人”就会拿起他们的照片

现在我想要的是查看来自朋友的帖子和来自我关注的人的照片的组合..我怎么能这样做哦,我按照它可以返回的方式按照日期订购

photo 
photo 
post 
post 
post 
photo 
post 

如果它的1个查询可能像

那么我可能无法输出
<?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;

}
?>

1 个答案:

答案 0 :(得分:1)

代码可以使用一点优化,但想法很清楚:

$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
      }
   }
}