如何通过对一个数据表的多次查询来获取多个表数据

时间:2019-04-20 06:43:49

标签: php mysql

如何通过对一个jquery dataTable进行多次查询来获取多个表数据。 我想获取多个查询的多个表数据到一个数据表。我可以根据我的代码执行一个查询吗,我尝试了MySQL UNION,不适合我。

Fetch.php

$query1 = "SELECT SUM(score) AS marks, from_date FROM table1 WHERE stat = 0 GROUP BY name ";
$statement = $db->prepare($query1);
$statement->execute();
$output = array('data' => array());
$count = $statement->rowCount();
if($count > 0) {

while($row = $statement->fetch(PDO:: FETCH_OBJ)) {

    $score = $row->marks;
    $date = $row->from_date;
    $Team = "Team 1";

$output['data'][] = array( $score,$date,$Team);     
 } // /while 
}// if num_rows

$query2 = "SELECT SUM(marks) AS marks, from_date FROM table2 WHERE stat = 0 GROUP BY name ";
$statement = $db->prepare($query2);
$statement->execute();
$output = array('data' => array());
$count = $statement->rowCount();
if($count > 0) {

while($row = $statement->fetch(PDO:: FETCH_OBJ)) {

    $score = $row->marks;
    $date = $row->from_date;
    $Team = "Team 2";

$output['data'][] = array( $score,$date,$Team);     
}
}// if num_rows
echo json_encode($output);

html

<table id="Table">
    <thead>
      <tr>
        <th>Score</th>
        <th>Start Date</th>
        <th>Team</th>
      </tr>
    </thead>
    <tbody>

    </tbody>
</table>

<script>    
var score;
$(document).ready(function(){
score = $('#Table').DataTable({
    'ajax': 'fetch.php',
    'order': []
    });
});
</script>

Table structer

1 个答案:

答案 0 :(得分:2)

您可以使用UNION ALL来获取结果。

  

注意:-两个表列都应该相同,否则会出现错误。

$result = [];
try {
  $conn = new PDO('mysql:host=HOST;dbname=DB;charset=utf8mb4', 'USERNAME', 'PASSWORD');
  $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  $conn->beginTransaction();

  $stmt1 = $conn->prepare("SELECT SUM(score) AS marks, from_date FROM table1 WHERE stat = 0 GROUP BY name UNION ALL SELECT SUM(marks) AS marks, from_date FROM table2 WHERE stat = 0 GROUP BY name ");
  $stmt1->execute();
  $result[]  = $stmt1->fetchAll(PDO::FETCH_ASSOC);
  $conn->commit();

} catch (PDOException $e) {
   echo $e->getMessage();
}   
echo json_encode($result);

对于团队变量,您可以尝试

SELECT SUM(score) AS marks, from_date,'Team1' AS team FROM table1 WHERE stat = 0 GROUP BY name 

和另一个查询

SELECT SUM(marks) AS marks, from_date, 'Team2' AS team FROM table2 WHERE stat = 0 GROUP BY name