MySQL全部加入三个表

时间:2015-01-15 21:25:11

标签: php mysql

有一个Q / A讨论系统,有三个表,用于三个级别的Q / A评论。表3(三级评论:GPcommentsFollowup2)与表2(二级评论:GPcommentsFollowup)相关,表2与表1(一级评论:GPcomments)相关。级别2和级别3实际上是级别1的后续注释。我想提取每个用户的贡献,显示用户贡献的级别的树。例如:

L1-- Title:
|--L2-- Title:
    |--L3-- Title:
    |--L3-- Title:
|--L2-- Title:
    (no L3 contributed)
|--L2-- Title:
    |--L3-- Title:
    |--L3-- Title:
    |--L3-- Title:
L1-- Title:
    (no L2 and L3 contributed)

我尝试了下面的代码,但返回值为空。有没有任何建议。

function userGroupContributions($pdo, $topicGroupId, $userId1){
$query= 'SELECT L1.commentTitle AS L1T, L1.commentId AS L1Id, L2.commentTitle AS L2T, L2.commentFollowupId AS L2Id, L3.commentTitle AS L3T, L3.commentFollowup2Id AS L3Id FROM GPcomments AS L1
        FULL OUTER JOIN GPcommentsFollowup AS L2 ON L1.commentId = L2.commentId
        FULL OUTER JOIN GPcommentsFollowup2 AS L3 ON L2.commentFollowupId = L3.commentFollowupId
        WHERE (L1.userId=? OR L2.userId=? OR L3.userId=?) AND topicSessionId=?';
$stmt = $pdo->prepare($query);
$stmt->execute(array($userId1, $userId1, $userId1, $topicGroupId));
$rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
foreach ($rows as $row) {
    $L1Id = $row['L1Id'];
    $L2Id = $row['L2Id'];
    $L3Id = $row['L3Id'];
    $L1T = htmlspecialchars_decode($row['L1T']);
    $L2T = htmlspecialchars_decode($row['L2T']);
    $L2T = htmlspecialchars_decode($row['L2T']);

    $data .= '<div>'.$L1T.'</div>';
}
return $data;

}

1 个答案:

答案 0 :(得分:0)

我用这段代码解决了这个问题:

$query= 'SELECT L1.commentTitle AS L1T, L1.commentId AS L1Id, L1.commentsTypeId AS L1Type, L2.commentTitle AS L2T, L2.commentFollowupId AS L2Id, L2.commentsTypeId AS L2Type, L3.commentTitle AS L3T, L3.commentFollowup2Id AS L3Id, L3.commentsTypeId AS L3Type FROM (SELECT * FROM GPcomments ORDER BY submitDate DESC) AS L1
        LEFT OUTER JOIN (SELECT * FROM GPcommentsFollowup ORDER BY submitDate DESC) AS L2 ON L1.commentId = L2.commentId
        LEFT OUTER JOIN (SELECT * FROM GPcommentsFollowup2 ORDER BY submitDate DESC) AS L3 ON L2.commentFollowupId = L3.commentFollowupId
        WHERE (L1.userId=? AND L1.topicSessionId=?) OR (L2.userId=? AND L2.topicSessionId=?) OR (L3.userId=? AND L3.topicSessionId=?)
        UNION
        SELECT L1.commentTitle AS L1T, L1.commentId AS L1Id, L1.commentsTypeId AS L1Type, L2.commentTitle AS L2T, L2.commentFollowupId AS L2Id, L2.commentsTypeId AS L2Type, L3.commentTitle AS L3T, L3.commentFollowup2Id AS L3Id, L3.commentsTypeId AS L3Type FROM (SELECT * FROM GPcomments ORDER BY submitDate DESC) AS L1
        RIGHT OUTER JOIN (SELECT * FROM GPcommentsFollowup ORDER BY submitDate DESC) AS L2 ON L1.commentId = L2.commentId
        RIGHT OUTER JOIN (SELECT * FROM GPcommentsFollowup2 ORDER BY submitDate DESC) AS L3 ON L2.commentFollowupId = L3.commentFollowupId
        WHERE (L1.userId=? AND L1.topicSessionId=?) OR (L2.userId=? AND L2.topicSessionId=?) OR (L3.userId=? AND L3.topicSessionId=?)';