如何使用ssp.class.php连接两个表

hoc*_*man 5 php mysql datatables

我开始使用DataTables Table插件用于jQuery并遇到了一些问题.我在这里使用示例代码.

我有MySQL表女巫看起来像那样:

id | 名字| father_id

father_idid在同一表中的值在不同的行中.所以,如果我想知道父亲的名字,我必须在同一张桌子上搜索WHERE id = father_id.但DataTable所做的只是显示MySQL表的内容.

在我的DataTable中,我希望显示如下数据:

id | 名字| father_name | father_id

因此,当DataTable从MySQL表中获取数据时,但在创建表之前,我想要更改当时father_id在MySQL中同一行中的值的列值.我想father_name通过特别搜索来添加它father_id.

Gyr*_*com 8

正如PaulF指出的那样,您需要使用JOIN或子查询来从同一个表中检索父亲的名字.

我假设您正在使用ssp.class.php基于您提到的示例在服务器端处理数据.

ssp.class.php不支持联接和子查询,但有一种解决方法.诀窍是使用子查询,如下面的$table定义所示.替换table为子查询中的实际表名.

$table = <<<EOT
 (
    SELECT 
      a.id, 
      a.name, 
      a.father_id, 
      b.name AS father_name
    FROM table a
    LEFT JOIN table b ON a.father_id = b.id
 ) temp
EOT;

$primaryKey = 'id';

$columns = array(
   array( 'db' => 'id',          'dt' => 0 ),
   array( 'db' => 'name',        'dt' => 1 ),
   array( 'db' => 'father_id',   'dt' => 2 ),
   array( 'db' => 'father_name', 'dt' => 3 )
);

$sql_details = array(
   'user' => '',
   'pass' => '',
   'db'   => '',
   'host' => ''
);

require( 'ssp.class.php' );
echo json_encode(
   SSP::simple( $_GET, $sql_details, $table, $primaryKey, $columns )
);
Run Code Online (Sandbox Code Playgroud)

您还需要编辑ssp.class.php和替换所有FROM `$table`with的实例FROM $table以删除反引号.

确保所有列名都是唯一的,否则用于AS指定别名.

笔记

还有github.com/emran/ssp存储库,其中包含增强的ssp.class.php支持JOIN.

链接

请参阅jQuery DataTables:使用WHERE,JOIN和GROUP BY与ssp.class.php获取更多信息.