2012-05-09 69 views
1

解決方案:訂購多的SUM在笨加入

$query = $this->db->query(" 
    SELECT *, SUM(views.times) AS sum 
    FROM channel 
    RIGHT JOIN video 
    ON channel.channel_id = video.channel_id 
    LEFT JOIN user 
    ON channel.user_id = user.user_id 
    LEFT JOIN views 
    ON channel.channel_id = views.channel_id 
    GROUP BY channel.channel_name 
    ORDER BY sum DESC 
"); 

我有一個返回的項目清單的查詢。

function getfrontpage(){ 
    $this->db->select('*'); 
    $this->db->from('channel');  
    $this->db->join('video', 'channel.channel_id = video.channel_id' , 'right'); 
    $this->db->join('user', 'channel.user_id = user.user_id'); 
    $this->db->group_by("channel.channel_name"); 
    $query = $this->db->get(); 
    return $query->result(); 
} 

現在我想從另一個表中訂購這些SUM,我該如何實現這一目標?

下面是從表圖片: view table

我想要的結果通過總的「次」的總和每個「頻道了」提前

感謝排序

回答

2

我建議通過$this->db->query()代替運行。

很高興通過CodeIgniters AR函數獲取簡單的值。但是在某些情況下,構建查詢字符串會更容易。

你的情況:

$query = $this->db->query(" 
SELECT channel_id, SUM(times) AS sum 
FROM channel 
GROUP BY channel_id 
ORDER BY sum DESC 
"); 

您也可以通過DB-逃脫最值>查詢()!

$this->db->query(" 
SELECT name 
FROM table_name 
WHERE id = ? 
", array(1)); 
+0

你能告訴我這個查詢應該是什麼嗎?我的查詢技能並不好。我以前從未使用SUM。 – Kozmk12

+0

你希望從哪個表中選擇SUM()? –

+0

我想要按照他們的「次數」來排序頻道,就像上面的圖片一樣,第一個頻道應該是頻道= 21,因爲times =(117 + 1)是最高的 – Kozmk12

1

是不是像$this->db->order_by("channel_id", "desc");那麼簡單?這會按照channel_id的降序排列結果。

+0

我想你誤解了我,我需要他們對每個頻道的「times」行中的數字總和進行排序。所以第一個將是channel = 21,因爲times =(117 + 1)是最大的數字,依此類推。 – Kozmk12

1

假設在你的問題中顯示的表稱爲times_table,並具有USER_ID的關鍵,CHANNEL_ID,您可以使用下面的代碼加入times_table到您的查詢,以便在「時間」欄可排序通過。

$this->db->join("times_table", "times.user_id=channel.user_id, times.channel_id=channel.channel_id", "left"); 
// You've already grouped by channel_name, so grouping by channel_id is probably not necessary. 
$this->db->order_by("SUM(times_table.times) DESC"); 

N.B.我剛猜到你顯示的表的名字是times_table。