CakePHP SQL查询计数
我有一个关于CakePHP SQL查询的问题。我需要从提供店铺id的数据库中获取产品,然后对产品进行计数。我只需要Product.url和它的计数 这将在普通SQL中实现以下功能:CakePHP SQL查询计数,sql,cakephp,Sql,Cakephp,我有一个关于CakePHP SQL查询的问题。我需要从提供店铺id的数据库中获取产品,然后对产品进行计数。我只需要Product.url和它的计数 这将在普通SQL中实现以下功能: SELECT url,COUNT(*) as count FROM products GROUP BY url ORDER BY count DESC; 这一个我曾经得到所有与商店有关的产品: $this->Product->find('all', array('conditions' => ar
SELECT url,COUNT(*) as count FROM products GROUP BY url ORDER BY count DESC;
这一个我曾经得到所有与商店有关的产品:
$this->Product->find('all', array('conditions' => array('Product.shop_id'=>$id)));
这是正确的,但我需要将上面的SQL查询转换为CakePHP
我试过这样的方法:
$this->Product->find('count', array('conditions' => array('Product.shop_id'=>$id),
'fields'=>array('Product.url','Product.id'),
'order'=>'count DESC',
'group'=>'Product.url'));
这只返回一个int。但如果我在mysql服务器中运行上面的SLQ查询,我会得到两列:url和count。如何使用CakePHP获得相同的结果?最简单的方法是:
$this->Product->query("SELECT url,COUNT(*) as count FROM products GROUP BY url ORDER BY count DESC;");
…至少对我来说是这样。最简单的方法是:
$this->Product->query("SELECT url,COUNT(*) as count FROM products GROUP BY url ORDER BY count DESC;");
…至少对我来说是这样。请尝试以下代码:
$this->Product->virtualFields['CNT_PRODUCTS'] = 0;
$this->Product->find('count', array('conditions' => array('Product.shop_id' => $id),
'fields' => array('Product.id', 'Product.url', 'count(*) as CNT_PRODUCTS'),
'order' => array('CNT_PRODUCTS' => 'DESC'),
'group' => 'Product.url'));
请尝试以下代码:
$this->Product->virtualFields['CNT_PRODUCTS'] = 0;
$this->Product->find('count', array('conditions' => array('Product.shop_id' => $id),
'fields' => array('Product.id', 'Product.url', 'count(*) as CNT_PRODUCTS'),
'order' => array('CNT_PRODUCTS' => 'DESC'),
'group' => 'Product.url'));
您可以尝试以下方法:
$data = $this->Post->query(
"SELECT COUNT(id),MONTH(created) FROM posts GROUP BY YEAR(created), MONTH(created);"
);
您可以尝试以下方法:
$data = $this->Post->query(
"SELECT COUNT(id),MONTH(created) FROM posts GROUP BY YEAR(created), MONTH(created);"
);
请参阅此链接:请参阅此链接:通常最好利用“虚拟字段”实现此目的:通常最好利用“虚拟字段”实现此目的: