将三个插入语句分成三个表

时间:2013-08-06 12:50:35

标签: php mysql

我有以下插入语句:

$sql ="INSERT INTO `firm`(name, VAT, active) VALUES ('$name', '$VAT', '$active')"; 

$sql = "INSERT INTO `area`(name, hub_name, fk_hub_id) VALUES ('$areaname',(SELECT `name` from hub WHERE name = '$hub_name'), (SELECT `id` from hub WHERE name = '$hub_name'))";

$sql ="INSERT INTO 'contactdetails'
        (fk_firm_id,
         address_physical_line_1,
         address_physical_line_2,
         address_physical_line_3,
         address_physical_line_4,
         address_physical_line_5,
         address_physical_line_6,
         address_physical_line_7,
         address_physical_code,
         address_postal_line_1,
         address_postal_line_2,
         address_postal_line_3,
         address_postal_line_4,
         address_postal_line_5,
         address_postal_line_6,
         address_postal_line_7,
         address_postal_code,
         fax_1,
         fax_2,
         phone_1,
         phone_2,
         phone_3,
         phone_4)
VALUES      ( (SELECT `id`
           FROM   firm
           WHERE  name = '$name'),
          '$address_physical_line_1',
          '$address_physical_line_2',
          '$address_physical_line_3',
          '$address_physical_line_4',
          '$address_physical_line_5',
          '$address_physical_line_6',
          '$address_physical_line_7',
          '$address_physical_code',
          '$address_postal_line_1',
          '$address_postal_line_2',
          '$address_postal_line_3',
          '$address_postal_line_4',
          '$address_postal_line_5',
          '$address_postal_line_6',
          '$address_postal_line_7',
          '$address_postal_code',
          '$fax_1',
          '$fax_2',
          '$phone_1',
          '$phone_2',
          '$phone_3',
          '$phone_4')  ";

我是否必须使用事务语句来运行这三个查询。我从未使用过交易报表。一个陈述取决于其他陈述的值。

2 个答案:

答案 0 :(得分:0)

默认情况下,MySQL将AUTO_COMMIT设置为true。这意味着脚本中的每个查询都将在之后执行。

这允许您执行以下操作:

// Here I admit that the table is empty, with an auto-incremented id.
INSERT INTO test VALUES ('', 'First');
INSERT INTO test ('', SELECT value FROM test WHERE id = "1");

在这里,您将插入第一行id=1, value="First",然后id=2, value="First"

答案 1 :(得分:0)

我不确定是否真的理解你的问题但如果你需要执行几个SQL请求,保证它们全部完成或 none 完成后,您必须显式创建并提交事务:

START TRANSACTION
INSERT ...
INSERT ...
INSERT ...

-- All is ready, apply "all at once"
COMMIT

http://dev.mysql.com/doc/refman/5.0/en/commit.html


为了清楚(?),从里面你的事务中,所有的SQL语句似乎都是“像往常一样”执行。但是从外部世界(其他事务/连接到您的SQL服务器),在您COMMIT您的事务之前不会出现任何更改 - 然后所有更改将出现“一次全部”。