thinkphp:数据库查询,嵌套别的表的查询(别的表做子查询)

例子

  1. 从 vendors 表中选择记录。
  2. 在 vendors 表中,筛选出具有满足以下条件的 vendor_code 值:
    • 对应的采购订单(在 po_headers_all 表中)存在未完全接收的采购行(在 po_lines_all 表中)。
    • 相应的采购订单状态为 "已签核"。
    • 采购行的数量大于已接收数量。
  3. 查询结果按照 vendor_code 字段降序排列,并限制返回的结果集的起始位置和数量。

代码

php 复制代码
$data['all_info'] = Db::table('vendors')
    ->alias('d')
     ->whereExists(function ($query) {
        $query->table('po_headers_all')
            ->alias('a')
            ->join(['po_lines_all'=>'b'], 'a.po_num = b.po_num')
            ->where('b.quantity', '>', Db::raw('b.quantity_received'))
            ->where('a.status', '已签核')
            ->where('a.vendor_code = d.vendor_code');
    })
    ->order('vendor_code', 'desc')
    ->limit($start,$pageSize)
    ->select();

逐句解析

  • $data['all_info'] = Db::table('vendors'): 创建了一个变量 $data['all_info'],用于存储查询结果。使用 Db::table('vendors') 指定了要查询的数据表为 "vendors"。

  • ->alias('d'): 使用别名 "d" 来表示数据表 "vendors"。

  • ->whereExists(function ($query) { ... }): 使用 whereExists 方法来指定一个子查询。子查询中的条件将用来检查是否存在满足条件的记录。

  • $query->table('po_headers_all')->alias('a'): 在子查询中,指定要查询的数据表为 "po_headers_all",并使用别名 "a" 来表示该表。

  • ->join(['po_lines_all'=>'b'], 'a.po_num = b.po_num'): 将数据表 "po_headers_all" 与 "po_lines_all" 进行连接,连接条件是 "a.po_num = b.po_num"。

  • ->where('b.quantity', '>', Db::raw('b.quantity_received')): 在连接后的数据表中,添加条件 "b.quantity > b.quantity_received"。这个条件用来筛选数量未完全接收的记录。

  • ->where('a.status', '已签核'): 添加条件 "a.status = '已签核'",用来筛选状态为 "已签核" 的记录。

  • ->where('a.vendor_code = d.vendor_code'): 添加条件 "a.vendor_code = d.vendor_code",将子查询中的 vendor_code 与主查询中的 vendor_code 进行比较,以确保查询结果中的记录是符合条件的。

  • ->order('vendor_code', 'desc'): 根据 vendor_code 字段降序排序查询结果。

  • ->limit($start, $pageSize): 指定查询结果的分页限制,从 $start 开始,取 $pageSize 条记录。

  • ->select(): 执行查询操作,获取符合条件的记录,并将结果返回给变量 $data['all_info']。

查询总数量同理(注:去掉了限制条件)

php 复制代码
$data['total'] = Db::table('vendors')
    ->alias('d')
    ->whereExists(function ($query) {
        $query->table('po_headers_all')
            ->alias('a')
            ->join(['po_lines_all'=>'b'], 'a.po_num = b.po_num')
            ->where('b.quantity', '>', Db::raw('b.quantity_received'))
            ->where('a.status', '已签核')
            ->where('a.vendor_code = d.vendor_code');
    })
    ->count();
相关推荐
草莓熊Lotso1 小时前
【C++ 基于微服务的即时通讯系统】etcd + brpc 从安装到服务注册发现全链路实战
网络·数据库·c++·redis·微服务·etcd
Lethehong7 小时前
Oracle 加个字段,目标库就报错?KFS 用“先拆后组“打通异构 DDL
数据库·oracle
Web极客码7 小时前
锁定真正的磁盘卡顿:我用 OpenCode 配合 eBPF 诊断 NVMe 队列深度延迟与 I/O 写放大
数据库·oracle
cspttty8 小时前
2027用户研究求职准备:应用统计学如何补齐研究设计与业务表达
大数据·数据库
yu_zhidun8 小时前
企业电脑监控软件怎么选:别只看功能清单,先看这 6 个底层能力
开发语言·电脑·php·域智盾系统
roman_日积跬步-终至千里9 小时前
【数据Agent论文·查询与语义|05】Spider:为什么换一个数据库,模型就不会查了?
数据库·数据分析
李纲明9 小时前
WordPress 白屏排查手册:关插件、换主题、开调试、查 PHP(附停手信号)
开发语言·php·wordpress·故障排查·白屏·插件冲突
猫咪很可爱9 小时前
Oracle RAC 启动失败排查:私网通信与内核参数优化实战
运维·数据库·oracle
XLYcmy9 小时前
《数字经济赋能城市低碳治理的路径研究检索报告》审阅与修改指导意见——基于完整检索报告体例的完整性诊断、学术规范核查与方法论纠偏 上
数据库·ai·chatgpt·文心一言·检索·知网·豆包
泡海椒9 小时前
JQuick-SQL 快速开始:注册内存表并执行查询
数据库·windows·sql