簡體   English   中英

我如何合並來自兩個mysql查詢的數據

[英]How can i combine data from two mysql queries

我早些時候問過這個問題,但是似乎沒人給我我想要的答案。

那么,如何合並來自兩個獲取每列的mysql查詢的數據,或者如何合並獲取兩個查詢中指定的每列的兩個mysql查詢的數據?

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

查詢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返回照片。 如果說我跟隨“某人”,它將獲取他們的照片

現在我想要的是查看朋友發帖和我關注的人的照片的組合..我該怎么做哦,我要按日期返回ORDER BY DATE

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;

}
?>

該代碼可以使用一些優化,但是思路很明確:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM