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


     例子

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

    代码

    1. $data['all_info'] = Db::table('vendors')
    2. ->alias('d')
    3. ->whereExists(function ($query) {
    4. $query->table('po_headers_all')
    5. ->alias('a')
    6. ->join(['po_lines_all'=>'b'], 'a.po_num = b.po_num')
    7. ->where('b.quantity', '>', Db::raw('b.quantity_received'))
    8. ->where('a.status', '已签核')
    9. ->where('a.vendor_code = d.vendor_code');
    10. })
    11. ->order('vendor_code', 'desc')
    12. ->limit($start,$pageSize)
    13. ->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']

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

    1. $data['total'] = Db::table('vendors')
    2. ->alias('d')
    3. ->whereExists(function ($query) {
    4. $query->table('po_headers_all')
    5. ->alias('a')
    6. ->join(['po_lines_all'=>'b'], 'a.po_num = b.po_num')
    7. ->where('b.quantity', '>', Db::raw('b.quantity_received'))
    8. ->where('a.status', '已签核')
    9. ->where('a.vendor_code = d.vendor_code');
    10. })
    11. ->count();

  • 相关阅读:
    php获取文件扩展名的三种方法
    LRTimelapse 6 for Mac(延时摄影视频制作软件)
    html,css之emmet语法
    Docker的安装
    论文阅读:2015ResNet深度残差网络(待补充)
    腾讯云我的世界mc服务器配置选择和价格表
    python如何读写excel
    RustDay04------Exercise[21-30]
    文件上传 [GXYCTF2019]BabyUpload1
    Java中Iterator迭代器有哪些功能呢?
  • 原文地址:https://blog.csdn.net/weixin_46001736/article/details/132664841