0

这是我的标签表:

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);
4

1 回答 1

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);
于 2013-01-05T01:43:54.330 回答