MySQL选择子查询

时间:2011-11-28 20:45:12

标签: mysql joomla1.7

这就是我现在所拥有的。

    $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。

1 个答案:

答案 0 :(得分: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列表中有奇怪的子查询。