将嵌套查询转换为sql视图

时间:2014-03-27 05:31:08

标签: mysql view

我有这三个不同的查询。这些查询给我结果独立正确。现在我想将这三个查询合并为单个查询或视图,以便从一个查询中轻松获得结果。

$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)";

1 个答案:

答案 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 (...);

但由于您没有发布表格结构或输出格式,因此您必须填写详细信息以获得所需内容。