2011-12-22 108 views
2

我想按「今日」,「本週」,「本月」,「所有時間」排序文章。問題是我的查詢總結了一張表中的選票並從另一張表中獲取了文章,這使得查詢對我來說真的很複雜,而且我不確定我是否正確地做了這件事。今天,周,月PhP訂單...不工作

無論如何,我有一個像http://web.com/top.php?time=頁「一段時間在這裏」我用下面的代碼來選擇文章立足於什麼時候用戶選擇,而不是「一段時間在這裏」

$time = preg_replace('#[^a-z]#i', '', $_GET["time"]); 

    if (!$time) { //Today 
    $date = "WHERE TO_DAYS(NOW()) - TO_DAYS(stories.st_date) = 1"; 
    } 
    else if ($time == "Week") { //This Week 
    $date = "WHERE TO_DAYS(NOW()) - TO_DAYS(stories.st_date) <= 7"; 
    } 
    else if ($time == "Month") { //This Month 
    $date = "WHERE TO_DAYS(NOW()) - TO_DAYS(stories.st_date) <= 31"; 
    } 
    else if ($time == "All") { //All Time 
    $date = ""; 
    } 
    else { 
    header("Location: http://www.web.com/"); 
    exit; 
    } 

$sql = ("SELECT stories.*, SUM(votes.vote_value) as 'total_votes' FROM stories JOIN votes ON stories.id = votes.item_name ".$date." GROUP BY stories.id ORDER BY total_votes DESC LIMIT 10") or die (mysql_error("There was an error in connection")); 

這似乎沒有任何工作; DI不明白爲什麼,在我看來它應該,但我比較新的PHP和MySQL。那麼任何人都可以提出問題在這裏?

我的數據庫結構讓您更好地理解系統。

案例表

enter image description here


投票表

enter image description here

+0

在您的腳本中運行sql之前,將變量$ date打印到屏幕上並查看該值。然後嘗試在phpmyadmin中運行,看看它是一個PHP或SQL的問題。 – ChelseaStats

+0

也你真的想比較item_name(varchar)與id(int)? – ChelseaStats

+0

嗯,$日期是正確的我在所有情況下都會迴應 – Ilja

回答

1

嘗試

SELECT stories.*, SUM(votes.vote_value) as 'total_votes' 
    FROM stories JOIN votes ON stories.id = votes.item_name 
    WHERE votes.item_name=$date 
    GROUP BY stories.id ORDER BY total_votes DESC LIMIT 10 

或類似的,想想你想實現什麼,然後邏輯重寫SQL查詢 在phpmyadmin直到你得到正確的輸出之前把它放入php。

+0

votes.item_name = $ date?所以例如where votes.item_name = TO_DAYS(NOW()) - TO_DAYS(stories.st_date)<= 31? – Ilja

+0

好吧,這似乎工作在phpmyadmin gona在網站上測試它)) – Ilja

+0

當我使用不同的查詢例如TO_DAYS(stories.st_date)<= 7(30等..)它會返回相同的結果 – Ilja