如何在服务器端处理模式下使用JOIN进行数据库查询

2024-01-14

我正在使用 jQuery DataTables 作为我的视图列表。我使用了服务器端处理模式,该模式非常适用于大型数据集。但我的问题是我只能使用单个数据库表来完成此操作。

使用多个表的自定义查询怎么样?JOIN我的代码无需改变太多?

所以我有这个:

HTML

<table id="CustomerList" class="table table-striped table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th colspan="7"> <center>Customer Information<center></th>
            <th colspan="1"> <center>Actions<center></th>
        </tr>
        <tr>
            <th>ID</th>
            <th>First Name</th>
            <th>Last Name</th>
            <th>Gender</th>
            <th>Phone Number</th>
            <th>Country</th>
            <th>Postcode</th>
            <th>Edit</th>
        <!--     <th>Edit</th>
            <th>Delete</th> -->
        </tr>
    </thead>
    <tbody>
    </tbody>
</table>

Ajax

<script type="text/javascript">
$(document).ready(function() {
    $.fn.dataTable.ext.legacy.ajax = true;
    var table = $('#CustomerList').DataTable( {
       "processing": true,
       "serverSide": true,
       "ajax": "api/customer/all",
       "columnDefs": [
            { 
                "targets": 7,
                "render": function(data, type, row, meta){
                   // return '<a href="/qms/public/customer/' + row[0] + '/edit">Edit</a>';  
                   return "<a class='btn btn-small btn-info' href='<?php echo URL::to('customer').'/';?>"+row[0]+"/edit'><span class='glyphicon glyphicon glyphicon-edit' aria-hidden='true'></span></a>";  
                }
            }            
        ]        
    });
    var tt = new $.fn.dataTable.TableTools( $('#CustomerList').DataTable() );
    $( tt.fnContainer() ).insertBefore('div.dataTables_wrapper');
});

控制器

public function apiGetCustomers()
{
    /*=================================================================*/
    /*
     * Script:    DataTables server-side script for PHP and PostgreSQL
     * Copyright: 2010 - Allan Jardine
     * License:   GPL v2 or BSD (3-point)
     */

    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * Easy set variables
     */

    /* Array of database columns which should be read and sent back to DataTables. Use a space where
     * you want to insert a non-database field (for example a counter or static image)
     */
    $aColumns = array('id', 'firstname', 'lastname', 'gender', 'phone_num', 'country', 'postcode' );

    /* Indexed column (used for fast and accurate table cardinality) */
    $sIndexColumn = "phone_num";

    /* DB table to use */
    $sTable = "customers";

    /* Database connection information */
    $gaSql['user']       = "postgres";
    $gaSql['password']   = "postgres";
    $gaSql['db']         = "qms";
    $gaSql['server']     = "localhost";



    /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
     * If you just want to use the basic configuration for DataTables with PHP server-side, there is
     * no need to edit below this line
     */

    /*
     * DB connection
     */
    $gaSql['link'] = pg_connect(
        " host=".$gaSql['server'].
        " dbname=".$gaSql['db'].
        " user=".$gaSql['user'].
        " password=".$gaSql['password']
    ) or die('Could not connect: ' . pg_last_error());


    /*
     * Paging
     */
    $sLimit = "";
    if ( isset( $_GET['iDisplayStart'] ) && $_GET['iDisplayLength'] != '-1' )
    {
        $sLimit = "LIMIT ".intval( $_GET['iDisplayLength'] )." OFFSET ".
            intval( $_GET['iDisplayStart'] );
    }


    /*
     * Ordering
     */
    if ( isset( $_GET['iSortCol_0'] ) )
    {
        $sOrder = "ORDER BY  ";
        for ( $i=0 ; $i<intval( $_GET['iSortingCols'] ) ; $i++ )
        {
            if ( $_GET[ 'bSortable_'.intval($_GET['iSortCol_'.$i]) ] == "true" )
            {
                $sOrder .= $aColumns[ intval( $_GET['iSortCol_'.$i] ) ]."
                    ".($_GET['sSortDir_'.$i]==='asc' ? 'asc' : 'desc').", ";
            }
        }

        $sOrder = substr_replace( $sOrder, "", -2 );
        if ( $sOrder == "ORDER BY" )
        {
            $sOrder = "";
        }
    }

    /*
     * Filtering
     * NOTE This assumes that the field that is being searched on is a string typed field (ie. one
     * on which ILIKE can be used). Boolean fields etc will need a modification here.
     */
    $sWhere = "";
    if ( $_GET['sSearch'] != "" )
    {
        $sWhere = "WHERE (";
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( $_GET['bSearchable_'.$i] == "true" )
            {
                if($aColumns[$i] != 'id') // Exclude ID for filtering
                {
                    $sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string( $_GET['sSearch'] )."%' OR ";
                }
            }
        }
        $sWhere = substr_replace( $sWhere, "", -3 );
        $sWhere .= ")";
    }

    /* Individual column filtering */
    for ( $i=0 ; $i<count($aColumns) ; $i++ )
    {
        if ( $_GET['bSearchable_'.$i] == "true" && $_GET['sSearch_'.$i] != '' )
        {
            if ( $sWhere == "" )
            {
                $sWhere = "WHERE ";
            }
            else
            {
                $sWhere .= " AND ";
            }
            $sWhere .= $aColumns[$i]." ILIKE '%".pg_escape_string($_GET['sSearch_'.$i])."%' ";
        }
    }


    $sQuery = "
        SELECT ".str_replace(" , ", " ", implode(", ", $aColumns))."
        FROM   $sTable
        $sWhere
        $sOrder
        $sLimit
    ";

    $rResult = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());

    $sQuery = "
        SELECT $sIndexColumn
        FROM   $sTable
    ";
    $rResultTotal = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
    $iTotal = pg_num_rows($rResultTotal);
    pg_free_result( $rResultTotal );

    if ( $sWhere != "" )
    {
        $sQuery = "
            SELECT $sIndexColumn
            FROM   $sTable
            $sWhere
        ";
        $rResultFilterTotal = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error());
        $iFilteredTotal = pg_num_rows($rResultFilterTotal);
        pg_free_result( $rResultFilterTotal );
    }
    else
    {
        $iFilteredTotal = $iTotal;
    }

    /*
     * Output
     */
    $output = array(
        "sEcho" => intval($_GET['sEcho']),
        "iTotalRecords" => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData" => array()
    );

    while ( $aRow = pg_fetch_array($rResult, null, PGSQL_ASSOC) )
    {
        $row = array();
        for ( $i=0 ; $i<count($aColumns) ; $i++ )
        {
            if ( $aColumns[$i] == "version" )
            {
                /* Special output formatting for 'version' column */
                $row[] = ($aRow[ $aColumns[$i] ]=="0") ? '-' : $aRow[ $aColumns[$i] ];
            }
            else if ( $aColumns[$i] != ' ' )
            {
                /* General output */
                $row[] = $aRow[ $aColumns[$i] ];
            }
        }
        $output['aaData'][] = $row;
    }

    echo json_encode( $output );

    // Free resultset
    pg_free_result( $rResult );

    // Closing connection
    pg_close( $gaSql['link'] );


}

在我的控制器中你可以看到$aColumns其中包含我想要在表中获取的表列customers

如果我想要自定义查询来获取如下数据怎么办:

$query = "SELECT a.id as crmid, b.name, a.title, a.firstname, a.surname, a.disposition, a.gross, a.created_at, a.phone_num FROM forms a INNER JOIN users b ON a.agent_id = b.id;";

所以我有内部联接而不是只有一张表。


有一个技巧可以使用JOIN无需过多修改代码。

更改这一行:

$sTable = "customers";

to:

$sTable = 
   "( 
      SELECT a.id AS crmid, b.name 
      FROM forms a 
      INNER JOIN users b ON a.agent_id = b.id 
    ) table";

我简化了上面的查询只是为了代码清晰。只需确保所有列名称都是唯一的,否则在需要时使用别名。

然后使用列名/别名$aColumns多变的。对于上面的查询,它将是

$aColumns = array('crmid', 'name');
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在服务器端处理模式下使用JOIN进行数据库查询 的相关文章

  • jquery.find() 可以只选择直接子项吗?

    我应该向 jQuery find 提供什么参数来选择元素子元素而不选择其他元素 我不能用 gt 引导选择器 而用 将选择所有后代 而不仅仅是直接子代 我知道 jQuery children 但这是一个库 因此用户能够提供自己的选择器 并且我
  • 交换关联数组中的两个项目

    Example arr array apple gt sweet grapefruit gt bitter pear gt tasty banana gt yellow 我想调换一下柚子和梨的位置 这样数组就变成了 arr array ap
  • PNG 透明度问题 - 带有黑色阴影的褪色图像 - IE 中的边框

    我使用图像旋转器在主页上显示一些图像 所有图像均为 PNG 格式 问题出在 IE 7 8 中 图像旁边有黑色阴影 我花了几个小时来解决这个问题 但仍然不知道问题出在哪里以及如何删除它 没有人有类似的问题和提示吗 如何解决 尝试使用 img
  • 使用 JavaScript 使链接保持活动状态并在单击时显示悬停效果

    I am struggling to make this work I d like to make it where if O F is clicked the hover state stays active if another li
  • 随机组合 MySQL 数据库中的两个单词

    我有一个包含名词和形容词的数据库 例如 id type word 1 noun apple 2 noun ball 3 adj clammy 4 noun keyboard 5 adj bloody ect 我想创建一个查询 它将抓取 10
  • Jquery/Javascript 上传和下载文件,无需后端

    是否可以在没有后端服务器的情况下在 JavaScript 函数中下载和上传文件 我需要导出和导入由 JavaScript 函数生成的 XML 我想创建按钮 保存 xml 来保存文件 但我不知道是否可行 另一方面 我希望将 XML 文件直接上
  • 将div设置为隐藏,延时后可见

    我试图在 X 时间后 也许甚至在随机时间之后 但现在我们只做固定时间 在黑色背景上出现一个黄色方块 function initialSetup if document getElementById yellow null document
  • 如果循环中内存超出,我可以在 for 循环中抛出异常吗?

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 如何处理 foreach 循环中发生
  • PHP HEREDoc (EOF) 语法在 Sublime Text 3 上突出显示与正斜杠的差异

    我不熟悉 Sublime Text 3 如何使用语法突出显示 例如 如果它纯粹依赖于主题 或者它内置于主题运行的标准中 但就我而言 使用 PHP 的 HERE 文档和转发存在一些语法突出显示差异斜线 一旦出现正斜杠 ST3 就会认为以下所有
  • CURL 中的 data-urlencode 是什么意思?

    我搜索了很多个小时试图弄清楚 php curl 中的 data urlencode 是什么 我尝试过这个 但我认为这是不对的 xmlpost object1 file https www lob com goblue pdf 在文档中是 d
  • 如何使用 JQuery 动态排序

    如果我有一个下拉列表和一个列表框 有没有办法使用 JQuery 根据下拉列表对列表框进行排序 举个例子会很有帮助 这会改变下拉菜单中的顺序 您必须根据自己的标准设置顺序
  • 使用 JQuery 更改元素的顺序

    有人知道我做错了什么吗 我正在尝试更改某些图像的显示顺序 我希望每次按下按钮时图像都会向右 向左移动一个位置 这是我尝试过的 但没有运气 任何帮助或见解将不胜感激 rightShift click function img hide var
  • 一次播种多行 laravel 5

    我目前正在尝试为我的用户表播种 如果我像这样尝试 2 行 就会失败 如果我只使用单个数组而不是 users 数组内的 2 个数组来创建一些假数据 那么效果很好 我做错了什么 正确的方法是什么 class UserTableSeeder ex
  • 如何更改此 jquery 插件的时区/时间戳?

    我正在使用这个名为 timeago 的插件 在这里找到 timeago yarp com 它工作得很好 只是它在似乎不同的时区运行 我住在美国东部 费城时区 当我将准确的 EST 时间放入 timeago 插件时 比如 2011 05 28
  • 内部 while 循环不工作

    这是我项目网页上的代码片段 这里我想显示用户选择的类别 然后想显示属于该类别的主题 在那里 用户可以拥有多个类别 这没有问题 我可以在第一个 while 循环中打印所有这些类别 问题是当我尝试打印主题时 结果只显示一行 但每个类别中有更多主
  • 为什么 Composer 降级了我的包?

    php composer phar update这样做了 删除了 2 3 0 软件包并安装了整个 2 2 5 Zend Framework php composer phar update Loading composer reposito
  • post php mysql 的拆分关键字

    我有一个表存储帖子 ID 它的标签如下 Post id Tags 1 keyword1 keyword2 keyword3 我想循环遍历该表中的每一行并执行以下操作 将关键字1 关键字2 关键字3放入新表中 word id word val
  • jQuery 对象相等

    如何确定两个 jQuery 对象是否相等 我希望能够在数组中搜索特定的 jQuery 对象 inArray jqobj my array 1 alert deviceTypeRoot deviceTypeRoot False alert d
  • Spring Rest 和 Jsonp

    我正在尝试让我的 Spring Rest 控制器返回jsonp但我没有快乐 如果我想返回 json 但我有返回的要求 完全相同的代码可以正常工作jsonp我添加了一个转换器 我在网上找到了用于执行 jsonp 转换的源代码 我正在使用 Sp
  • fullCalendar 未显示正确的结束日期

    我正在看调试页面 http jsbin com wukofacaxu edit js outputFullCalendar 官方网站的 我想安排一个活动时间为 22 09 2015 至 30 09 2015 dd mm yyyy 但它只显示

随机推荐

  • 如何在 PostgreSQL 中生成虚拟表来生成日期序列?

    我想生成一个日期列表 希望与另一个表连接 但我不知道要使用什么语法 类似于 SELECT dates date transactions account id transactions amount FROM as dates LEFT J
  • 订票系统:数据库访问问题

    我正在创建一个巴士票预订系统 我创建了一个名为 Traveler 的数据库和两个分别名为 Useriden 和 BusDB 的表 在 aspx cs 文件 注册页面 中 我正在检查重复的用户名 但它只是导航到下一页 我已经尝试了一切 但无法
  • Rails 中的composed_of - 何时使用它?

    什么时候应该使用 ActiveRecordcomposed of http apidock com rails ActiveRecord Aggregations ClassMethods composed of类方法 就我个人而言 我认为
  • 将Java程序运行到另一个程序中[重复]

    这个问题在这里已经有答案了 可能的重复 在java程序中执行另一个jar https stackoverflow com questions 1320476 execute another jar in a java program 我尝试
  • 是否可以以编程方式向场景添加行?

    我想在每个 SpecFlow 测试的开头添加相同的行 这一行指定了几个场景的列表 这些场景会随着时间的推移而改变 因此为每个测试维护这个列表是不可行的 例如 Given I have set my site theme to
  • 发送用户 ID 和 access_token

    我正在使用 React 前端在 ASP NET Core 2 1 应用程序中实现 Auth0 一旦用户进行身份验证 我就会得到access token and an id token 我的目的很明确access token是授予对我的 AP
  • Chef-solo 从 bash 脚本获取日志

    我正在通过 Chef 执行 shell 脚本 如下所示 execute Run postgres data migration do command home ubuntu build target infra base psql10 mi
  • 单一职责原则有什么用?

    我试图理解单一职责原则 但我很难理解这个概念 我正在阅读 Lucian Paul Torje Adrian Ianculescu Kamalmeet Singh 所著的 Java 设计模式和最佳实践 一书 在这本书中我正在阅读单一职责原则章
  • Webpack 不排除 node_modules

    我正在使用 webpack 作为我正在构建的 Node 框架 尽管我应该承认 我应该使用 gulp 当我包含 EJS 模块时 webpack 将其包含在编译的源代码中 即使我明确告诉它排除 node modules 目录 module ex
  • 创建一个常量但本地的数组

    有时我需要针对单个方法的硬编码查找表 我也可以创建这样一个数组 在方法本身本地 类内静态 第一种情况的示例 public int Convert int i int lookup new 1 2 4 8 16 32 666 return l
  • gradle远程调试流程

    我正在添加GRADLE OPTS系统环境变量为 Xdebug Xrunjdwp transport dt socket server y suspend y address 5005 我已经从 IntelliJ IDEA 为此套接字创建了远
  • 如何修复错误“反编译的 .class 文件字节码版本 52.0 (Java 8)

    当我在模拟器上测试我的应用程序时 它工作正常 但是当我在真正的 android 10 0 版本 手机上运行该应用程序时 log cat 显示我根本无法理解的错误 这是非常令人困惑的 因为它在一部手机 较低版本 上运行良好 但在另一部手机 A
  • 如何在heroku cedar堆栈上使用virtualenv进行pip卸载?

    我尝试使用以下命令卸载 heroku 上的模块 heroku run bin python bin pip 卸载任何东西 Pip 在 app 树中显示该模块 然后声称已卸载该模块 但再次运行相同的命令显示它安装在 app 树中的同一位置 有
  • OpenLayers 通过 Popups 窃取点击事件

    为什么 FramedCloud 弹出窗口会窃取弹出窗口内的点击事件 current popup new OpenLayers Popup FramedCloud featurePopup f geometry getBounds getCe
  • Maven Surefire 测试插件运行测试,即使它们被排除:

    我排除插件中除我的测试套件之外的所有测试
  • 想要使用Excel VBA选择网站上的按钮

    我想使用 Excel 来浏览网页 但该网站不像普通网站 亚马逊 谷歌等 那样使用 ID 该网站是http www scoopmae com http www scoopmae com 我如何选择 预订演示 按钮 我通常会使用 getelem
  • 在引用任何静态成员之前调用静态构造函数

    根据文档 静态构造函数用于初始化任何静态数据 或执行只需执行一次的特定操作 它被自动调用before创建第一个实例或引用任何静态成员 但我在 stackoverflow 帖子中看到了以下来自 C 规范的引用 如果类中存在静态构造函数 第 1
  • Vim 编译时支持 Python 但看不到 sys 版本

    我编译了 Vim 的开发版本 同时支持 Python 2 和 Python 3 的输出vim version has python dyn and python3 dyn在里面 我运行配置文件 G configure enable pyth
  • Powershell:如何阻止脚本中显示错误?

    例如 当我的 PowerShell 脚本尝试为不存在的服务器 在本例中为 bla 创建 SQL Server 对象时 PowerShell 会以红色显示大量 PowerShell 错误 由于我的脚本检查了 在此类调用以及显示和记录错误之后
  • 如何在服务器端处理模式下使用JOIN进行数据库查询

    我正在使用 jQuery DataTables 作为我的视图列表 我使用了服务器端处理模式 该模式非常适用于大型数据集 但我的问题是我只能使用单个数据库表来完成此操作 使用多个表的自定义查询怎么样 JOIN我的代码无需改变太多 所以我有这个