2011-11-28 131 views
0

這是我目前所擁有的。MySQL選擇子查詢

$db =& JFactory::getDBO(); 

    $query = $db->getQuery(true); 

    $query->select('`#__catalog_commit`.`id` as id, `#__catalog_commit`.`date` as date, COUNT(`#__catalog_commit_message`.`commit_id`) as count, 
    (SELECT COUNT(`#__catalog_commit_message`.`type`) as count_notice FROM `#__catalog_commit_message` WHERE `#__catalog_commit_message`.`type` = 1 GROUP BY `#__catalog_commit_message`.`type`) as count_notice, 
    (SELECT COUNT(`#__catalog_commit_message`.`type`) as count_warning FROM `#__catalog_commit_message` WHERE `#__catalog_commit_message`.`type` = 2 GROUP BY `#__catalog_commit_message`.`type`) as count_warning, 
    (SELECT COUNT(`#__catalog_commit_message`.`type`) as count_error FROM `#__catalog_commit_message` WHERE `#__catalog_commit_message`.`type` = 3 GROUP BY `#__catalog_commit_message`.`type`) as count_error'); 
    $query->from('#__catalog_commit_message'); 
    $query->leftjoin('`#__catalog_commit` ON `#__catalog_commit`.`id` = `#__catalog_commit_message`.`commit_id`'); 
    $query->group('`#__catalog_commit_message`.`commit_id`'); 
    $query->order('`#__catalog_commit`.`id` DESC'); 

我有什麼是2代表具有以下結構:

catalog_commit 
============== 
id 
date 

catalog_commit_message 
====================== 
id 
commit_id 
type 
message 

基本上我想有每個不同類型的每組項目的消息的計數。在我有它實際上選擇每一行(這是正常的),但我正在尋找一種方式(如果可能,尼克爾)有在查詢中的每個消息類型的計數。

編輯:只是想補充說它是一個JModelList。

回答

0

從我所收集,這應該是您查詢:

SELECT c.id 
     ,c.date 
     ,count(cm.commit_id) as ct_total 
     ,sum(CASE WHEN cm.type = 1 THEN 1 ELSE 0 END) AS count_notice 
     ,sum(CASE WHEN cm.type = 2 THEN 1 ELSE 0 END) AS count_warning 
     ,sum(CASE WHEN cm.type = 3 THEN 1 ELSE 0 END) AS count_error 
FROM catalog_commit c 
LEFT JOIN catalog_commit_message cm ON cm.commit_id = c.id 
GROUP BY c.id, c.date 
ORDER BY c.id DESC 

您曾在LEFT JOIN扭轉你的表的順序。另外,你在SELECT列表中有奇怪的子查詢。

+0

非常好,我真的需要更多地學習MySQL。謝謝。 – Manhim