如何在同一DATETIME上连接两个表时绕过冗余记录?

时间:2018-02-08 13:41:40

标签: php

我正在DATETIME上的forumPosts和PostImages上执行左连接。我正在执行此连接,以便我可以访问存储在每个表中的项目。我正在获得多余的帖子,这些帖子是该连接的所有组合的产物,因为这些记录具有相同的时间。冗余帖子都具有针对每个讨论区域的特定topic_id,因为它们来自该单个记录的所有可能组合。我没有将冗余帖子发送到数据库中的forumPostsPostImages表,因为错误发生在view_topic文件中的查询中。如果我可以请求帮助完善我的查询/加入,以便记录更具针对性。我想知道是否有办法在同一时间专门识别记录。请参阅论坛下面的屏幕截图,其中包含多余的帖子。

此代码适用于视图主题页面(view_topic.php)。请注意,我执行查询以使用forumPosts加入ImagePosts,这应该只返回匹配的topic_id的记录。我现在相信我在DATETIME上获得了加入的所有产品。我需要知道如何将查询限制为特定记录。

    $query5 = 'SELECT * FROM forumPosts LEFT JOIN PostImages ON 
    forumPosts.DATETIME = PostImages.ImageDATETIME where 
    topic_id="'.$tid.'"ORDER BY replyIndex ASC';


    $statement = $db->prepare($query5);
    $statement->execute();

    //count returned rows
    $count = $statement->rowCount();
    echo "<h1>".$count."</h1>";

    $posts = $statement->fetchAll();

    $statement->closeCursor();
    echo "<table>";
    foreach ($posts as $post){
    if ($post['post_type'] == "r"){
    $post_id = $post['post_id'];
    echo "<tr bgcolor='beige'><td>". $post['post_author'] . "</td >
    <td>". $post['post_title']."</td><td>". $post['post_body']; 
    if (!empty($post['ID']) && ($post['type']== 'i')) {
        echo "<img src='getImage.php?id=".$post['ID']."'>";
    } elseif (!empty($post['ID']) && ($post['type']== 'm')) {
        echo '<audio controls>'; 
        echo '<source 
    src="data:audio/mp3;base64,'.base64_encode($post['image']).'"‌​>';
        echo '</audio>';
    } elseif (!empty($post['ID']) && ($post['type']== '3')) {
        echo '<audio controls>'; 
        echo '<source 
    src="data:audio/mp3;base64,'.base64_encode($post['image']).'"‌​>';
        echo '</audio>';
        echo '<p>Buy the full track with PayPal:</p>'. $post['URL'];
    }

    echo "</td><td>". $post['topic_id']."</td><td>". $post['DATETIME']. 
    "</td><td>". $post['replyIndex']. "</td><td>".$post['post_type']."
    </td>";

Capture of my forum showing redundant posts

image showing PostImages Image showing forumPosts

1 个答案:

答案 0 :(得分:0)

我不得不在代码中添加另一个连接条件: $ query5 ='SELECT * FROM forumPosts LEFT JOIN PostImages ON forumPosts.DATETIME = PostImages.ImageDATETIME AND forumPosts.topic_id = PostImages.topic_id_image其中topic_id =“'。$ tid。'”ORDER BY replyIndex ASC'; 谢谢你帮我解决了!