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

Posted

技术标签:

【中文标题】如何在服务器端处理模式下使用 JOIN 进行数据库查询【英文标题】:How to use database query with JOIN in server-side processing mode 【发布时间】:2015-12-30 18:13:47 【问题描述】:

我正在为我的视图列表使用 jQuery DataTables。我使用了服务器端处理模式,该模式特别适用于大型数据集。但我的问题是我只能使用单个数据库表来做到这一点。

如果我的代码不做太多更改,如何使用多个带有JOIN 的表进行自定义查询?

所以我有这个:

HTML

<table id="CustomerList" class="table table-striped table-bordered" cellspacing="0" >
    <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>

阿贾克斯

<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;";

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

【问题讨论】:

您是在询问分页数据吗?我对 PHP 或 Laravel 不熟悉,但通过 Google 快速发现:https://laracasts.com/discuss/channels/general-discussion/jquery-datatables-and-laravel-server-side-implementation 【参考方案1】:

我知道这篇文章已经很老了,但它给了我线索。我遇到了同样的挑战,偶然发现了@Óscar Sánchez 的回应。

仅针对可能遇到相同问题并需要帮助的任何人,这就是我所做的。

    首先我创建了一个视图
    CREATE VIEW economic AS select tbl_pay.idno, tbl_pay.name, tbl_pay.amount, tbl_pay.cat, tbl_pay.item, tbl_pay.code, tbl_rev.t_id, tbl_sect.s_name, tbl_pay.bnk, DATE_FORMAT(tbl_pay.paydate, '%d %M %Y') AS PayDate, tbl_pay.reno, tbl_pay.slip, tbl_pay.cStatus, tbl_pay.cvdate, YEAR(paydate) AS PayYr 
    FROM tbl_pay 
    INNER JOIN tbl_rev ON tbl_pay.cat = tbl_rev.revid 
    INNER JOIN tbl_sect ON tbl_rev.t_id = tbl_sect.t_id 
    WHERE tbl_rev.t_id = 1 AND YEAR(paydate)=YEAR(NOW()) ORDER BY tbl_pay.cat, tbl_pay.name
    创建名为“经济”的视图后,我现在只在服务器端文件中添加了该表名,如下所示:
    <?php

include('dd_connection.php');

$column = array('code', 'cat', 'name', 'item', 'amount', 'bnk', 'reno', 'cvdate', 'PayDate');

$query = "
SELECT * FROM economic 
";

if(isset($_POST['filter_cat']) && $_POST['filter_cat'] != '')

 $query .= '
 WHERE cat = "'.$_POST['filter_cat'].'" 
 ';


if(isset($_POST['order']))

 $query .= 'ORDER BY '.$column[$_POST['order']['0']['column']].' '.$_POST['order']['0']['dir'].' ';

else

 $query .= 'ORDER BY name ASC ';

and other lines of code below....

现在根据您的 mysql 版本,在创建视图时,您可能需要将视图名称保留为 经济,不带标点符号,或者像这样添加打开和关闭标点符号 '经济'

现在,当您在线上传服务器端文件时,不要忘记重复创建在线视图的相同过程,否则您的页面将不显示任何记录。

【讨论】:

【参考方案2】:

您需要创建一个包含关系的视图。

    在 MySql 中创建 VIEW:

    CREATE VIEW 'the_view' AS SELECT a.id, a.num_factura_proveedor, b.nombre_comercial
    FROM compras a
    INNER JOIN terceros b ON a.tercero_id = b.id
    

    在服务器端脚本:

    $sTable = "the_view";
    
    //the columns of the view
    $aColumns = array('id' , 'num_factura_proveedor', 'nombre_comercial');
    $sIndexColumn = "id";
    

【讨论】:

【参考方案3】:

在不过多修改代码的情况下使用JOIN有一个技巧。

改变这一行:

$sTable = "customers";

到:

$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');

【讨论】:

嗨。我尝试了您的建议,但出现错误,查询失败:错误:FROM 中的子查询必须具有别名 LINE 3: FROM ( ^ HINT: For example, FROM (SELECT ...) [AS] foo. 这指向我行 $rResult = pg_query( $gaSql['link'], $sQuery ) or die(pg_last_error()); 非虚拟机。解决了这个问题。谢谢! 我必须通过将“$table”替换为“$table”来编辑库中的 ssp.class.php 文件。它现在按预期工作。 这可能已经快 6 年了,但在 2021 年完美运行!谢谢!

以上是关于如何在服务器端处理模式下使用 JOIN 进行数据库查询的主要内容,如果未能解决你的问题,请参考以下文章

存储库模式 - 如何正确处理 JOIN 和复杂查询?

巧用 Logstash 实现服务端文档 Join

MapReduce表连接操作之Reduce端join

如何在不使用 Join 的情况下处理引用其他表的相关子查询的问题

如何在超过 2 台服务器的主动/被动模式下进行 tcp 负载平衡?

Hadoop Join