这是我的标签表:
post_id tag topic
1 picture entertainment
1 camera entertainment
1 mobile technology
2 cable technology
这是我现在的 SQL(使用 Zend 框架):
$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);