sql >> Base de Datos >  >> RDS >> Mysql

Cómo fusionar tablas en MySQL

$insertSQL1 = "INSERT INTO sr1_full (`date`, `total_pending`, `appt_today`, `percent_appt_today`) SELECT `date`, `total_pending`, `appt_today`, `percent_appt_today` FROM `sr1`";

$insertSQL2 = "INSERT INTO sr2_full (`date`, `total_pending`, `appt_today`, `percent_appt_today`) SELECT `date`, `total_pending`, `appt_today`, `percent_appt_today` FROM `sr2`";

$insertSQL3 = "INSERT INTO sr3_full (`date`, `total_pending`, `appt_today`, `percent_appt_today`) SELECT `date`, `total_pending`, `appt_today`, `percent_appt_today` FROM `sr3`";

Añadir ; para combinar dos sentencias SQL.

Puede combinar estas consultas de esta manera.

$insertSQL_Single = $insertSQL1.";".$insertSQL2.";".$insertSQL3;

consulta resultante:

INSERT INTO sr1_full (`date`, `total_pending`, `appt_today`, `percent_appt_today`) SELECT `date`, `total_pending`, `appt_today`, `percent_appt_today` FROM `sr1`;INSERT INTO sr2_full (`date`, `total_pending`, `appt_today`, `percent_appt_today`) SELECT `date`, `total_pending`, `appt_today`, `percent_appt_today` FROM `sr2`;INSERT INTO sr3_full (`date`, `total_pending`, `appt_today`, `percent_appt_today`) SELECT `date`, `total_pending`, `appt_today`, `percent_appt_today` FROM `sr3`

He intentado esto usando PhpMyAdmin. la consulta fue exitosa

no puede ser ejecutado por mysql_query() . vamos a encontrar algunos otros trucos. tenemos que ejecutarlo por separado.

Usa mysqli para ejecutar esto

$mysqli = new mysqli("host","username","password", "databasename");
if (!$mysqli->multi_query($insertSQL_Single)) {
    echo "Multi query failed: (" . $mysqli->errno . ") " . $mysqli->error;
}
else
{
    echo "success";
}