我有一个数据库:
------------------------------
name |extension |filesize
------------------------------
abc | php | 12
def | php | 18
ghi | bat | 32
jkl | bat | 24
mno | php | 30
我想指定所有扩展名并汇总文件大小,因此它运行良好:
$sql= "SELECT extension, SUM(filesize) AS total FROM mytable GROUP BY extension";
$stmt = $pdo->query($sql);
while($row = $stmt->fetch(PDO::FETCH_BOTH)){
echo $row['extension'] . " - " . $row['1'] . "<br>";
}
输出结果为:
php - 60
bat - 56
但是现在我想将这些结果插入到一个新表中(当然使用PDO)。我想要一张新表:
---------------------
ext |sumfilesize
---------------------
php | 60
bat | 56
我想我必须在while循环中进行一些查询但是可以在查询中进行查询吗? 我该怎么做?
答案 0 :(得分:0)
只要您不在while循环中创建新表,就可以了。只需将查询插入到while循环中的数据库中,您就完成了。 代码应如下所示:
$sql= "SELECT extension, SUM(filesize) AS total FROM mytable GROUP BY extension";
$stmt = $pdo->query($sql);
while($row = $stmt->fetch(PDO::FETCH_BOTH)){
echo $row['extension'] . " - " . $row['1'] . "<br>";
$query = "INSERT INTO TableName (ext, sumfilesize) VALUES ($row['extension'], $row['1'])";
$query->execute();
}
答案 1 :(得分:0)
$sql="INSERT INTO myTotalTable (extension,total) SELECT extension,SUM(filesize) AS total FROM mytable GROUP BY extension";
$stmt = $pdo->query($sql);