0

这是我第一次使用多个INNER JOINS 编写代码,它们的关系只是一个表。

这就是我正在做的事情:

$table = $_POST['tabla'];
$campos = $_POST['campos'];
$campoRelacion = $_POST['campo_relacion'];

    **//Code that i forget to put**

   *// Create an array that will contain the fields
   $ field = array ();

   //walk the array of fields and is assigned to the array
   //that was created previously
    foreach ($ fields as $ val) {
      $ field [] = "". $ val. "";
    }

   //We separate the fields in the array with commas
   $ field = join (',', $ field);*


$mainTable = $table[0];


$sql = 'SELECT '.$field.'
        FROM '.$mainTable.' ';

for ($i = 1; $i<count($table); $i++) { 
    $curTable = $table[$i];
    $joinField = $campoRelacion[$i-1];
    $sql.= 'INNER JOIN '.$curTable.' 
            ON '.$mainTable.'.'.$joinField.' = '.$curTable.'.'.$joinField.' '; 
}

根据我发送的数据,这个输出将是这样的:

SELECT
slip_plantillas.nombre,
cat_reaseguradoras.nombre,
slips.numero_referencia,
slips.asegurado_original,
tipo_operaciones.nombre
FROM
slips
Inner Join slip_plantillas ON slips.slip_plantillaID = slip_plantillas.slip_plantillaID
Inner Join cat_reaseguradoras ON slips.cat_reaseguradoraID = cat_reaseguradoras.cat_reaseguradoraID
Inner Join tipo_operaciones ON slips.tipo_operacionID = tipo_operaciones.tipo_operacionID

如上表所示,代码滑动在连接中保持不变。

但是现在我有另一个 sql 语句,我想在其中滑动不恒定并更改联合。

查询如下所示:

SELECT
slip_dos_reasegurado.prima_cien,
slip_dos_reasegurado.porcentaje_aseguradora,
cat_reaseguradoras.nombre,
slip_dos_capas.capa,
slip_dos_capas.prima_capa,
slip_dos_pagos.cantidad,
slip_dos_pagos.referencia,
estatus.nombre,
slips.tipo_negocio
FROM
slips
Inner Join slip_dos_reasegurado ON slips.slipID = slip_dos_reasegurado.slipID
Inner Join slip_dos_capas ON slip_dos_capas.slip_dos_reaseguradoID = slip_dos_reasegurado.slip_dos_reaseguradoID
Inner Join slip_dos_pagos ON slip_dos_capas.slip_dos_capaID = slip_dos_pagos.slip_dos_capaID
Inner Join cat_reaseguradoras ON cat_reaseguradoras.cat_reaseguradoraID = slip_dos_reasegurado.cat_reaseguradoraID
Inner Join estatus ON estatus.estatusID = slip_dos_pagos.estatusID

如您所见,如果根据字段关系不相互混合,则关系不再是单个表。

4

1 回答 1

0

也许你需要这个?

<?php
$tables = array('tbl1','tbl2','tbl3','tbl4');
$columnTable = array('column1','column2','column3','column4');
$columnRelation =     array('column_relation1','column_relation2','column_relation3','column_relation4');


$mainTable = $tables[0];


$sql = 'SELECT *
    FROM '.$mainTable.' ';

foreach($tables as $index=>$tbl){
    if($index == 0) continue; //Normal only while you know that your array indexes start from 0, in other case you would need variable for this
    $sql .= 'INNER JOIN $tbl ON '.$tbl.'.'.$columnTable[$index].' = '.$tables[$index-1].'.'.$columnRelation[$index-1].' ';
}

echo $sql;
?>
于 2013-08-09T22:17:12.183 回答