2014-03-27 34 views
2

我有這三種不同的queries.These查詢給了我獨立導致correct.now我要合併這三種查詢到單個查詢或視圖來獲取導致一個查詢變得非常容易。轉換嵌套查詢到SQL視圖

$sql1 = "select * from user_post_like 
          inner join user_post 
          on user_post_like.postID = user_post.postID 
          where ((user_post.poster='$uID' AND user_post_like.userID!='$uID' ) OR (user_post.wallID='$uID' 
            AND user_post_like.userID!='$uID') 
            AND user_post_like.notificationStatus=0)"; 


    $sql2 = "select * from user_post_comment 
          inner join user_post 
          on user_post_comment.postID = user_post.postID 
          where ((user_post.poster='$uID' AND user_post_comment.commenter!='$uID') OR (user_post.wallID='$uID' AND user_post_comment.commenter!='$uID') 
          AND user_post_comment.notificationStatus=0)"; 


    $sql3 = "select * from user_post_share 
          inner join user_post 
          on user_post_share.postID = user_post.postID 
          where ((user_post.poster='$uID' 
AND user_post_share.Share_user_id!='$uID') OR (user_post.wallID='$uID' AND user_post_share.Share_user_id!='$uID')         AND 
user_post_share.notificationStatus=0)"; 

回答

0

這一切都取決於您的表結構以及您希望單個結果集的外觀。

如果你的三個表具有相同的結構,你可以使用UNION將它們合併:

$big_single_query = "$sql1 UNION $sql2 UNION $sql3"; 

如果它們不具有相同的結構,可以將三個獨立的查詢的邏輯組合成三表連接:

SELECT upl.*, upc.*, ups.* 
FROM user_post_like as upl 
LEFT JOIN user_post_comment as upc on ... 
LEFT JOIN user_post_share as ups on ... 
WHERE (...) and (...) and (...); 

但因爲你沒有張貼表格或您的輸出格式的結構,你必須填寫在細節上得到你想要的。

+0

的感謝!我有不同結構的表 – Swapnil

+0

然後使用連接語法。希望你不需要像在例子中那樣使用*,你最好選擇你的程序需要的列。 –