2016-04-01 97 views
0

我正在嘗試製作文章網站,但我想規範化當前數據庫。我有四個表格,每個表格都標記一個類別,但一個除外四個表格是:娛樂,生活方式,科學和文章。文章是娛樂,生活方式和科學所有條目的組合。我想刪除娛樂,生活方式和科學,只留下文章表,從而節省空間和提高性能。我遇到的唯一問題是使用通過獲取表格的最後一個ID生成隨機文章的查詢,然後獲取介於6和最大ID之間的隨機數。正在更新查詢,以反映規範化數據庫

我所有的表具有以下結構:id(唯一的),category(文章類型這是,即娛樂),title(文章標題),image(文章的圖片URL),link(URL ),Counter(本文觀看次數)和dateStamp(文章發表日期)。以下是我試圖根據規範化數據庫進行更新的查詢。

<?php 
    //SELECT the MAX id from the Entertainment table 
    $MAX_ID = $db->query("SELECT MAX(id) FROM Entertainment"); 

    //Get Max id value 
    $MAX_ID = $MAX_ID->fetch_array(); 
    $MAX_ID = $MAX_ID[0]; 

    //Create random number variable 
    $RAND_NUM; 

    //If the Max ID is less than 6, make $MAX_ID the $RAND_NUM 
    if ($MAX_ID < 6) { 
     $RAND_NUM = $MAX_ID; 

    } 

    //Else get a random value between 6 and the Max ID 
    else { 
     $RAND_NUM = mt_rand(6, $MAX_ID); 

    } 

    //Grab 6 articles by descending from the random number, example: If $RAND_NUM is 7, get all entries from 7-2 
    $resultSet = $db->query("SELECT * FROM Entertainment WHERE id <= $RAND_NUM ORDER BY id DESC LIMIT 6"); 

    if ($resultSet->num_rows != 0) { 
     //Booleans to check where we are at in the print off 
     $conditional = true; 
     $conditional2 = true; 
     echo "<div class='row'>"; 
     while ($rows = $resultSet->fetch_assoc()) { 
      $image = $rows["image"]; 
      $title = $rows["title"]; 
      $link = $rows["link"]; 
      $count = number_format($rows["Counter"]); 

      //Print off these articles on the left 
      if ($conditional == true && $conditional2 == true) { 
       echo "<div class='left'><a href='$link'><img src=$image><p>$title</p></a><p id='article-views'><span class='glyphicon glyphicon-fire'></span> $count Views</p></div>"; 

       $conditional2 = false; 
      } 

      //Print off these articles on the right 
      else { 
       echo "<div class='right'><a href='$link'><img src=$image><p>$title</p></a><p id='article-views'><span class='glyphicon glyphicon-fire'></span> $count Views</p></div><hr>"; 

       $conditional2 = true; 
      } 


     } 

     echo "</div>"; 
    } 


?> 

我應該如何更改/更新此查詢,以便從文章表中獲得隨機娛樂文章?我願意接受任何改善查詢性能的改變。

+0

僅供參考,您的舊方法假定低編號的文章編號從未刪除。 – Barmar

回答

0

而不是選擇一個隨機的結束ID,只是隨機化所有的行,並從他們中選擇6。

SELECT * 
FROM Articles 
WHERE category = 'Entertainment' 
ORDER BY RAND() 
LIMIT 6 

如果你需要避免ORDER BY RAND(),因爲它不執行不夠好,見How can i optimize MySQL's ORDER BY RAND() function?

+0

我聽說ORDER BY RAND()在表現上很糟糕,這就是爲什麼我一直在避免它。 – user2896120

+0

的確如此。看到我鏈接到的問題。 – Barmar

+0

您的表格是否足夠大,確實會導致性能問題,或者您只是假設它會。不要假設,衡量它。 – Barmar