【问题标题】:Insert row in table B on table A's insert query在表 A 的插入查询中在表 B 中插入行
【发布时间】:2011-03-10 00:11:30
【问题描述】:

使用 MySQL,我认为有一种方法可以关联,但也许我错了。

我有带有 userID 的表 A,和带有 userID 的表 B,它设置为删除 A.userID 以级联和删除 B.userID。

所以我有一个查询(使用 CI),在表 A 中插入信息,我想在表 B 中插入具有相同用户 ID(PK、AI)的行。有时它会在 B.userID 行中插入值,有时它会完全为空值。

关于如何做到这一点的想法?

谢谢。

【问题讨论】:

    标签: php mysql sql codeigniter


    【解决方案1】:

    我确实需要查看实际查询,但我相信这就是您要查找的内容。

    当您在 CodeIgniter 中插入数据时,您可以像这样获取插入的主键。

    $this->db->insert('A',$data);  //insert into the table with 'userID' as PK, AI
    
    $id_of_insert = $this->db->insert_id();
    
    $data_for_b = array(
        'field' => 'value',
        ...
        'userID' => $id_of_insert   //insert the captured PK from A and place in the FK field of B
    );
    
    $this->db->insert('B', $data_for_b);
    

    【讨论】:

    • 谢谢,很有魅力。希望我知道 insert_id 函数!
    • codeigniter.com/user_guide 是你的朋友。没有讽刺的意思,如果你已经知道这个,很抱歉。
    【解决方案2】:

    最简单的做法是编写一个存储过程来执行插入。这既可以在事务中进行插入,也可以接受将数据添加到 B 和 A 中的参数。然后您的查询将调用存储的过程,而不是直接插入。

    【讨论】:

      【解决方案3】:

      在这种方法中您应该考虑以下几点:

      1. 如果您的 auto_increment 为 BIGINT,则会给出错误的值。

      2. 如果您在读取值之前插入了一些东西,而其他人也插入了一些东西,您可能会得到错误的 id。我建议用独特的不同的东西来阅读价值。 (例如用户注册中的昵称)。

      【讨论】:

        猜你喜欢
        • 2020-04-22
        • 2015-01-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-05-12
        相关资源
        最近更新 更多