如何从两个独立的SQL表中选择最新日期


How to select the latest date from 2 separate SQL tables?

原始问题

我有一个代码,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;