如何从mysql结果中获取表名?

时间:2016-12-10 10:43:50

标签: php mysql join inner-join

MySQL查询如下

SELECT t1.*, t2.*, t3.*, t4.*, t5.*, t6.* FROM table1 t1 INNER JOIN table2 t2 INNER JOIN table3 t3 INNER JOIN table4 t4 INNER JOIN table5 t5 INNER JOIN table6 t6 order by t1.updated_time, t2.updated_time, t3.updated_time, t4.updated_time, t5.updated_time, t6.updated_time desc

从上面的查询我需要结果与他们各自的表名如

Array( [0] => stdClass Object ( [id] => 1 [cloumn1] => data1 [column2] => table3 [updated_time] => data1 ) [1] => stdClass Object ( [id] => 2 [cloumn1] => data1 [column2] => table1 [updated_time] => data2 ) )

这些表格的列数超过15列,可能会有所不同 如何通过修改查询来实现结果?

2 个答案:

答案 0 :(得分:1)

在进行查询后,您可以进行foreach循环以获取所有列名称。像这样的东西

while($row = mysqli_fetch_assoc($query)){
    foreach($row as $key => $value){
        echo "$key=$value";
    }
}
Update

如果您想在数据库中获取表名,可以尝试这样的方法。

$sql = "SHOW TABLES FROM database";
$result = mysqli_query($conn,$sql);

while ($row = mysqli_fetch_row($result)) {
    echo "Table: {$row[0]}\n";
}
  

更新

首先我们需要获取表名。由于您不知道表名,我们可以使用此代码

$tables = array();
$sql = "SHOW TABLES FROM database";
$result = mysqli_query($conn,$sql);

while ($row = mysqli_fetch_row($result)) {
    $tables[] = $row[0];
}

如果您有表格,可以将它们添加到数组中,同时滑动上面的代码

$tables = array("table1","table2","table3");

获取所有表后,我们可以从数据库开始

$data = array();
foreach($tables as $table){
    $query = "select * from $table";
    $res = mysqli_query($conn,$query);
    while($row = mysqli_fetch_assoc($res)){
        $i=1;
        foreach($row as $key => $value){
            $data[$i][$key][$value];
            $i++;
        }
    }
}

根据您的需要更新代码。这是一个例子

答案 1 :(得分:1)

另一种解决方案(由某些ORM使用)

1。创建表列表

<?php $tables = ['table1', 'table2', 'table3']; ?>

2。执行SHOW COLUMNS FROM表来分析表

http://dev.mysql.com/doc/refman/5.7/en/show-columns.html

<?php
$structures = [];
$structuresLinear = [];
foreach( $tables as $table ) {
  $query = mysqli_query('SHOW TABLES FROM ' . $table);

  while ($row = mysqli_fetch_row($query)) {
    $structures[$table][] = $row[0];
    $structuresLinear[] = sprintf('%s.%s as %s', $table, $row[0], $table . '_' . $row[0]);
  }
}

您的$structures每个表的所有字段都会显示,另一个$structuresLinear会重新命名不同的字段。

例如:['table1.id as table1_id', 'table1.name as table1_name', ...]

3。创建最终查询

<?php
$sql  = 'SELECT ';
$sql .= implode(', ', $structuresLinear);
$sql .= ' FROM ' . implode(' INNER JOIN ', $tables);
$sql .= ' ORDER BY ' . implode(', ',
  array_map(function($t) {
    return $t . '.updated_time';
  }, $tables)
);

?>

输出

你会有这样的事情:

SELECT
  table1.id as table1_id,
  table2.id as table2_id, table2.col2 as table2_col2, table2.col3 as table2_col3
FROM table1
  INNER JOIN table2
ORDER BY
  table1.updated_time,
  table2.updated_time

最后一个数组将是:

Array(
    [0] => Array(
        table1_id = table1.id,
        table2_id = table2.id,
        table2_col2 = table2.col2,
        table2_col3 = table2.col3,
    )
)

您还可以拆分每个$ key结果以获得表或创建multidim数组:)