我正在建立一个相当简单的网站来跟踪一些工作销售情况。它涉及一个mysql数据库,每个条目都有多个表。在大多数情况下,关系是切断和干燥的。但是,我有一个评论表,可以为同一个销售存储多个评论。我在注释表中有一个与主销售表的ID相关联的外键。我在总表和销售表之间有类似的安排,因为它存储了同一saleID的多个总金额。将这些插入数据库的最佳方法是什么?目前,我正在插入注释并获取该行的ID,然后插入总计并获取ID,然后使用注释ID和总ID将插入到sales表中。是否有更有效的方法而不是进行5次查询?
- 编辑:这是当前的代码。我对此很新,所以我不得不查看程序,看看你的意思。看起来它基本上就是我正在做的事情,但是为它创建一个方法,一旦我找到最有效的方法,我将会做的。
//Prepare the Queries
//Insert Gross Amounts Query
$grossQ = "INSERT INTO gross (commGross, storeGross, manGross, fiGross, flatGross) VALUES ('$commGross', '$storeGross', '$manGross', '$fiGross')";
//Insert Comments Query
$commentsQ = "INSERT INTO comments (comment, dealcomment, grosscomment) VALUES ('$otherComments', '$dealComments', $grossComments')";
//Insert Deal Query
$q = "INSERT INTO sales (make, model, location, vehtype, saletype, manager, county, flat, unitcount, armoramount, controlnumber, salesman, stock) VALUES ('$make', '$model', '$location', '$vehType', '$saleType', '$managerName', '$county', '$flat', '$unitCount', '$armorAmount', '$controlNumber', '$salesmanName1', '$stock')";
//Make database connection
$db = new db('palm_sales');
//Execute gross query and get the id of the row
$db->execute($grossQ);
$grossID = $db->getLastID();
//Execute comments query and get the id of the row
$db->execute($commentsQ);
$commentsID = $db->getLastID();
//Build Main Query
$q = "INSERT INTO sales (make, model, location, vehtype, saletype, manager, gross, comments, county, flat, unitcount, armoramount, controlnumber, salesman, stock) VALUES ('$make', '$model', '$location', '$vehType', '$saleType', '$managerName', '$grossID', '$commentsID', '$county', '$flat', '$unitCount', '$armorAmount', '$controlNumber', '$salesmanName1', '$stock')";
//Execute Main Query
$db->execute($q);
if(mysql_affected_rows() > 0)
{
echo "Success!";
}
else echo "Error: ".mysql_error();
答案 0 :(得分:1)
听起来你现在只执行3个查询 - mysql_insert_id()
不执行新查询,它会提供有关刚刚执行的插入的信息。
当您插入评论或总评估时,您需要插入销售表时不清楚。我想你会有这样的事情:
TABLE sales PK id
TABLE comments PK id FK sales_id
TABLE gross PK id FK sales_id
当您获得新的促销时,您会插入sales
表格。要添加新注释或粗略,请使用销售ID的外键插入该表。哪一部分不起作用?