php - 代码点火器 : complex query with join and limit

标签 php mysql codeigniter

我在 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/

相关文章:

mysql 搜索 like with text うえ

c# - 无法以 C# windows 形式连接到任何指定的 MySQL 主机

mysql - 将值显示为数组中的单个值

php - 销售基于 PHP 框架构建的脚本

javascript - 在博客中准备和显示代码示例的替代方法

javascript - 使用一个按钮提交表单,一个按钮使用 html 脚本发送到 emailmeform,另一个按钮发送到我的内部数据库

php - 将我的网站设置为公开后图像出现错误

php - 多个查询相互依赖

php - 从服务器 MySql 数据库更新本地服务器 MySql 数据库

PHP Codeigniter 错误:调用未定义的方法 ci_db_mysql_driver::result()