0

我有 3 张桌子questionsarticlespictures

每个表中的行包含一个 current_timestamp 列posted,并链接到一个 id。我想按时间戳对所有三个行的结果进行排序,并且只回显三个中的最新一个(例如:如果问题是来自 ID 的最新问题,则仅显示)

if(count($interests) != 0){ foreach($interests as $interests_following){
    $interestid = mysql_result(mysql_query("SELECT `id` FROM `interests` WHERE `name` = '$interests_following'"),0);
    $interestquestions = @mysql_result(mysql_query("SELECT `question_text`, `posted` FROM `questions` WHERE `interest` = '$interests_following'"),0);
    $interestarticles = @mysql_result(mysql_query("SELECT `article_title`, `posted` FROM `articles` WHERE `interest_id` = '$interestid'"),0);
    $interestpictures = @mysql_result(mysql_query("SELECT `interest_pic_title`, `posted` FROM `interest_pictures` WHERE `interest_id` = '$interestid'"),0);

echo '.$interests_following.': //<Only display 1 newest item (article/picture/question here>
4

4 回答 4

3

使用UNION ALL

SELECT posted 
FROM
(
    SELECT `question_text`, `posted` FROM `questions` 
    WHERE `interest` = '$interests_following'
    UNION ALL
    SELECT `article_title`, `posted` FROM `articles` 
    WHERE `interest_id` = '$interestid'
    UNION ALL
    SELECT `interest_pic_title`, `posted` FROM `interest_pictures` 
    WHERE `interest_id` = '$interestid'
) t
ORDER BY posted DESC LIMIT 1
于 2012-11-05T23:49:48.370 回答
0

要返回单行:

$sql = "SELECT * FROM WHERE `name`='$interests_following' ORDER BY `posted` DESC LIMIT 1";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);

所有的工作都在 SQL 中

ORDER BY `posted` DESC LIMIT 1

这命令结果首先具有最新的,然后只返回第一行。

如果您打算只返回 3 个表格中的一项,您有 2 个选择:

  • 从每个中获取一行,然后确定 PHP 中的最新
  • 使用 aUNION查找 SQL 中的单个最新行

后者减少了代码,但可能不太可读。

于 2012-11-05T23:48:48.623 回答
0

试试这个

$interestquestions = @mysql_result(mysql_query("SELECT `question_text`, `posted` FROM `questions` WHERE `interest` = '$interests_following' ORDER BY timestamp_field DESC limit 1"),0);


这将仅显示您的时间戳的最新数据库。

于 2012-11-05T23:49:43.297 回答
0

我将向您展示 SQL 查询,以便您了解我所做的;根据需要使其适应您的代码。

SELECT 
  (SELECT question_text 
     FROM questions ORDER BY posted DESC LIMIT 1 ),

  (SELECT article_title 
    FROM articles ORDER BY posted DESC LIMIT 1 ),

  (SELECT interest_pic_title 
    FROM interest_pictures ORDER BY posted DESC LIMIT 1)
;

这按时间戳 DESCending 排序,因此最新记录在前,然后将其限制为单个记录。结果将是question_text, article_title, interest_pic_title

于 2012-11-05T23:51:51.713 回答