如何从2个单独的SQL表中选择最新日期?

时间:2016-01-04 04:38:45

标签: php mysql pdo

原始问题

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

现在它只显示一个帖子,如果还有帖子。

1 个答案:

答案 0 :(得分:0)

您不需要循环,并且可以在使用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;