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();
相关推荐
悄悄敲敲敲7 小时前
MySQL表的约束
数据库·mysql
鼠爷ねずみ7 小时前
SpringCloud前后端整体开发流程-以及技术总结文章实时更新中
java·数据库·后端·spring·spring cloud
九皇叔叔7 小时前
MySQL 数据库 Read View 详解
数据库·mysql·mvcc·read view
Elastic 中国社区官方博客9 小时前
Elasticsearch:圣诞晚餐 BBQ - 图像识别
大数据·数据库·elasticsearch·搜索引擎·ai·全文检索
cui_win9 小时前
Prometheus实战教程 - Redis 监控
数据库·redis·prometheus
JIngJaneIL9 小时前
基于java + vue个人博客系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot
TG:@yunlaoda360 云老大9 小时前
华为云国际站代理商备份策略设置过程中遇到问题如何解决?
服务器·数据库·华为云
SelectDB10 小时前
Doris Catalog 已上线!性能提升 200x,全面优于 JDBC Catalog,跨集群查询迈入高性能分析时代
数据库·数据分析·apache
TAEHENGV10 小时前
进度跟踪模块 Cordova 与 OpenHarmony 混合开发实战
android·javascript·数据库
神秘面具男0310 小时前
MySQL 从基础到实践
数据库·mysql