You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CodeIgniter多条件关联查询获取专属库存楼层数量无结果求助

问题描述

我是PHP新手,使用CodeIgniter框架,目前有两个可正常运行的查询:

  • 获取库存中楼层数量的查询:
$data['Floors'] = $this->db
    ->get_where('tblcustomfieldsvalues', ['fieldid' => 75, 'fieldto' => 'inventory', 'value' => 'Floor'])
    ->num_rows();
  • 获取专属库存数量的查询:
$data['total_leads_exc'] = $this->db
    ->from('tblinventory_status')
    ->where('id',10)
    ->get()
    ->num_rows();

现在我想要获取库存中专属楼层的数量,尝试了如下关联查询,但未得到预期结果:

SELECT tblnleads.name FROM tblnleads 
    LEFT JOIN tblcustomfieldsvalues
        ON tblcustomfieldsvalues.id = tblnleads.id
    WHERE tblnleads.status = '10'
        AND tblcustomfieldsvalues.fieldid = '61'
        AND tblcustomfieldsvalues.fieldto = 'inventory'
        AND tblcustomfieldsvalues.value = 'Floors';
问题分析与解决方案

你的关联查询存在几个关键问题,以下是修正方案:

核心问题点

  1. 关联条件错误:tblcustomfieldsvalues.id = tblnleads.id逻辑不通,自定义字段表的id是自身主键,关联库存表应该用对应库存ID的字段(比如relid/fieldrelatedid这类字段,具体看表结构)。
  2. 查询目标不符:你需要统计数量,但原SQL查询的是name,应该用COUNT函数。
  3. 字段ID不一致:第一个查询用的fieldid是75,关联查询里写成了61,需确认正确的楼层字段ID。
  4. LEFT JOIN 被强制转为INNER JOIN:WHERE条件里加了自定义字段表的过滤规则,LEFT JOIN失去意义,直接用INNER JOIN更合适。

修正后的SQL查询

SELECT COUNT(DISTINCT tblnleads.id) AS exclusive_floor_count
FROM tblnleads
INNER JOIN tblcustomfieldsvalues
    ON tblcustomfieldsvalues.relid = tblnleads.id  -- 替换为你表中实际的关联字段
WHERE tblnleads.status = 10
    AND tblcustomfieldsvalues.fieldid = 75
    AND tblcustomfieldsvalues.fieldto = 'inventory'
    AND tblcustomfieldsvalues.value = 'Floor';

转成CodeIgniter Active Record写法

$data['exclusive_floor_count'] = $this->db
    ->select('COUNT(DISTINCT tblnleads.id) AS count')
    ->from('tblnleads')
    ->join('tblcustomfieldsvalues', 'tblcustomfieldsvalues.relid = tblnleads.id', 'inner')
    ->where('tblnleads.status', 10)
    ->where('tblcustomfieldsvalues.fieldid', 75)
    ->where('tblcustomfieldsvalues.fieldto', 'inventory')
    ->where('tblcustomfieldsvalues.value', 'Floor')
    ->get()
    ->row()->count;

注意事项

  • 先确认tblcustomfieldsvalues中关联库存表的字段名称,这是查询正确的核心。
  • 使用COUNT(DISTINCT)避免同一库存被重复统计(如果单条库存对应多条自定义字段记录)。

内容的提问来源于stack exchange,提问作者abs backup

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 01:01:12