这是我的标记表格:
post_id tag topic
1 picture entertainment
1 camera entertainment
1 mobile technology
2 cable technology
这是我的SQL(使用Zend Framework):
$select = $db->select();
$select->from(array('t' => 'tags'), array('count(*)', 't.topic'))
->joinInner(array('p' => 'posts'),'p.post_id = t.post_id')
->where('p.status = ?', self::STATUS_LIVE)
->where('t.topic= ?', $options);
return $db->fetchOne($select);
我想计算主题,每 ID 选择一个。在这种情况下,它将是:
entertainment: 1
technology: 2
我现在的结果是:
entertainment: 2
technology: 2
这是解决方案:
$select = $db->select();
$select->from(array('t' => new Zend_Db_Expr('(SELECT post_id,topic FROM tags group by post_id,topic)')), array('count(*)', 't.topic'))
->joinInner(array('p' => 'posts'), 'p.post_id = t.post_id', array())
->where('p.status = ?', self::STATUS_LIVE)
->where('t.topic= ?', $options)
->group("t.topic");
return $db->fetchOne($select);
答案 0 :(得分:0)
您可以使用此查询:
SELECT COUNT(*),topic FROM (SELECT post_id,topic FROM tags GROUP BY post_id,topic) t GROUP BY topic;
zend中的相同查询:
$select = $db->select();
$select->from(array('t' => new Zend_Db_Expr('(SELECT post_id,topic FROM tags group by post_id,topic)')), array('count(*)', 't.topic'))
->group("t.topic");
$db->fetchAll($select);