原始问题

我有一个带有while循环的代码可以获取很多东西,我遇到了while循环不能正确排序的问题。

在这种情况下,它仅排序最新发布的线程,我想要的是它检查数据库中最新的线程是发布还是发布。

$ handler是我的数据库连接变量,我使用PDO。

我当前的代码:

<?php
    $query = $handler->query('SELECT * FROM thread ORDER BY postdate DESC');

    while($fetch = $query->fetch(PDO::FETCH_ASSOC)){
        $rcount = $handler->query('SELECT COUNT(*) FROM threadpost WHERE t_id = ' . $fetch['t_id']);
        $queryTime = $handler->query('SELECT * FROM threadpost WHERE t_id =' . $fetch['t_id'] . ' ORDER BY postdate DESC');

        $fetchTime = $queryTime->fetch(PDO::FETCH_ASSOC);
        $rfetch = $rcount->fetch(PDO::FETCH_NUM);

        if(strtotime($fetch['postdate']) < strtotime($fetchTime['postdate'])){
            $fetch['postdate'] = $fetchTime['postdate'];
            $fetch['u_id'] = $fetchTime['u_id'];
        }
?>
<tr>
    <td><a href="<?php echo $website_url . 'thread/' . $fetch['t_id']; ?>" style="font-weight: bold;"><?php echo $fetch['title']; ?></a></td>
    <td><?php echo $rfetch[0]; ?></td>
    <td>
        <?php
            $monthNum  = substr($fetch['postdate'], 5, 2);
            $dateObj   = DateTime::createFromFormat('!m', $monthNum);
            echo $fetch['title'] . '<br />';
            echo substr($fetch['postdate'], 11, 8) . ' on ' . substr($fetch['postdate'], 8, 2) . ' ' . $dateObj->format('F') . ' ' . substr($fetch['postdate'], 0, 4) . '<br />';
            echo'by ' . $fetch['u_id'];
        ?>
    </td>
</tr>
<?php
    }
?>


我希望这有道理,很难解释。

我已经搜索了一下,发现可能需要使用join,但是我不知道该怎么做。



部分解决方案:

SELECT th.*, (count(po.t_id) + count(th.t_id)) AS amount, max(po.postdate) AS lastdate FROM thread th INNER JOIN threadpost po ON th.t_id = po.t_id GROUP BY po.t_id ORDER BY lastdate DESC


直到现在,如果其中也有帖子,它只会显示一个线程。

最佳答案

您不需要遍历,可以使用WHERE EXISTS在单个SQL语句中完成此操作,例如

SELECT *
FROM threadpost t1
WHERE EXISTS (SELECT 1 FROM thread WHERE t_id = t1.t_id)
ORDER BY postdate DESC;


(OR)可能使用简单的联接查询,例如

SELECT t1.*
FROM threadpost t1 JOIN thread t2 ON t1.t_id = t2.t_id
ORDER BY t1.postdate DESC;

关于php - 如何从2个单独的SQL表中选择最新日期?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34584754/

10-13 08:53