我希望将这些检索到的数据(两行)插入另一个称为临时子类别的(临时)表中。但是在该表中仅插入了一行。这段代码有什么问题?
<?php
require 'configuration.php';?>
<?php
if(isset($_POST['action'])) {
$sql_c = "SELECT c.catId, s.subCatId, s.subCatName
FROM category c, subcategory s
WHERE c.catId=s.catId AND c.catId='".$_POST['action']."' ;";
$result_c = $conn->query($sql_c);
if($result_c->num_rows>0) {
while($row = $result_c->fetch_assoc()) {
$ctId = $row['catId'];
$sctId = $row['subCatId'];
$sctname = $row['subCatName'];
$sql_d = "INSERT INTO presubcategory
(presubcatId,precatId,presubcatName)
VALUES('".$ctId."','".$sctId."','".$sctname."');";
$conn->query($sql_d);
}
}
}
?>
答案 0 :(得分:2)
您应该在这里创建一个包含两个原始表和简单联接的视图。
CREATE VIEW presubcategory AS
SELECT c.catId, s.subCatId, s.subCatName
FROM category c, subcategory s
WHERE c.catId=s.catId';
SELECT `subCatId` as preSubCatId,
`catId` as preCatId,
`subCatName` as preSubCatName
FROM presubcategory WHERE catid=?;
无需复制数据,它可以满足您对preSubCategory表的查询。
答案 1 :(得分:1)
正如aynber所指出的,您可以使用INSERT INTO SELECT语句来做到这一点:
<?php
require 'configuration.php';
if(isset($_POST['action'])) {
$sql = "INSERT INTO presubcategory
(presubcatId,precatId,presubcatName)
(
SELECT c.catId, s.subCatId, s.subCatName
FROM category c, subcategory s
WHERE c.catId=s.catId
AND c.catId='".$_POST['action']."'
);";
$conn->query($sql);
}
?>
这未经测试,但是我认为它应该可以解决问题,前提是您的select语句已经正常工作。