显示5个最新的论坛帖子

时间:2013-04-19 01:41:50

标签: php

所以我的数据库中有3个表,比如1_comments,2_comments和3_comments,我想在PHP中一次显示所有3个表的最新5个帖子,并按最近的时间排序。我的代码是:

<?php
  $row="";

  $link = mysql_connect("localhost","username","password");
  mysql_select_db("database");
  $query = "SELECT * from 1_comments  ORDER by timestamp DESC limit 5";
  $result = mysql_query($query);

  while($row = mysql_fetch_array($result)) {
    echo "<ul>";
    echo "<li>".$row['comment']."</li>";
    echo "</ul>";
  } 

  mysql_close($link);
?>

所以它从1_comments的评论行中收集了最近的5篇帖子,并按最近的时间戳排序,但我似乎无法让它同时适用于1_comments,2_comments和3_comments。

1 个答案:

答案 0 :(得分:0)

如果所有表格具有相同的结构,则可以使用UNION

类似的东西:

(SELECT * from 1_comments  ORDER by timestamp DESC limit 5)
UNION
(SELECT * from 2_comments  ORDER by timestamp DESC limit 5)
UNION
(SELECT * from 3_comments  ORDER by timestamp DESC limit 5)
ORDER BY timestamp DESC limit 5

但是,我会仔细研究数据库结构,并尝试将3个类似的表减少到只有一个。