0

私は3つのテーブルを持っています: questionsarticlesおよびpictures

各テーブルの行には current_timestamp 列が含まれておりposted、id にリンクしています。3 つすべての行の結果をタイムスタンプで並べ替え、3 つのうち最新のもののみをエコーし​​たい (たとえば、質問が 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 
  (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 に答える
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 つのテーブルから 1 つのアイテムのみを返す場合は、次の 2 つの選択肢があります。

  • それぞれから行をフェッチし、PHP で最新のものを決定します
  • a を使用しUNIONて、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 に答える