我在 codeigniter 中的查询如下所示,
$select = 'msg.*';
$this->db->select($select, FALSE)
->from(TBL_MESSAGES . ' as msg')
->join(TBL_PRODUCT . ' as p', 'msg.ProductId=p.Id');
$query = $this->db->order_by('msg.Id', 'DESC')->get();
if ($query->num_rows() > 0)
{
return $query->result_array();
}
这里我想要结果,前 10 个产品的所有消息,
但在上面的查询中,如果我放置 limit
那么它总共显示 10 条消息
任何人都可以帮助我如何对上述查询设置限制吗?
最佳答案
希望这对您有帮助:
要么这样做:
首先收集您的 10 个产品 ID,并将它们用于上面的查询 where_in
$product_ids = $this->db->select('Id')->limit(10)->get(TBL_PRODUCT)->result_array();
/* to select most recent msg with product id and name do like this, correct
if product_name column is wrong*/
$select = 'msg.*,p.Id,p.product_name';
/*$select = 'msg.*';*/
$query = $this->db->select($select, FALSE)
->from(TBL_MESSAGES . ' as msg')
->join(TBL_PRODUCT . ' as p', 'msg.ProductId=p.Id')
->where_in('p.Id',$product_ids)
->order_by('msg.Id', 'DESC')
->get();
if ($query->num_rows() > 0)
{
return $query->result_array();
}
或者您可以获取所有产品 ID 并使用 where
子句循环遍历它以获得所需的结果
/* to select most recent msg with product id and name do like this, correct
if product_name column is wrong*/
$select = 'msg.*,p.Id,p.product_name';
$product_ids = $this->db->select('Id')->get(TBL_PRODUCT)->result_array();
if ( !empty($product_ids))
{
foreach($product_ids as $pid)
{
$query = $this->db->select($select, FALSE)
->from(TBL_MESSAGES . ' as msg')
->join(TBL_PRODUCT . ' as p', 'msg.ProductId=p.Id')
->where('p.Id',$pid)
->order_by('msg.Id', 'DESC')
->get();
if ($query->num_rows() > 0)
{
$data[] = $query->result_array();
}
}
return $data;
}
了解更多:https://www.codeigniter.com/user_guide/database/query_builder.html#looking-for-specific-data
关于php - 代码点火器 : complex query with join and limit,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50349033/