dongyi2083 2016-01-05 12:45
浏览 111
已采纳

将表的默认值插入另一个表

Simplified version:

I have a table named books (book_id, book_title) where book_id is the primary key and of type serial (so it is assigned automatically without me inserting it).

I also have another table named book_version (id, book_id, book_version) where book_id is foreign key to the first table.

With a form I take the book title and version. I insert the title into the first table and have to insert the generated book_id along with version into the second table.

How can I do that without having 3 separate queries (one insert for first table, one select to get it's id and one insert for the second table)?

The idea here is that the same book may have been published several times with slight changes, so i want to keep track of different versions.

  • 写回答

4条回答 默认 最新

  • dongyangben6144 2016-01-05 12:48
    关注

    Use an after insert trigger on the first table:

    http://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html

    An after insert trigger can reference the inserted row and then you only have to run 1 statement to insert the version.

    You only have to insert the first row via PHP, and your trigger is installed in the database and does the work after that.

    That is the best way to do it, IMO.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥35 引用csv数据文件(4列1800行),通过高斯-赛德尔法拟合曲线,在选取(每五十点取1点)数据,求该数据点的曲率中心。
  • ¥20 程序只发送0X01,串口助手显示不正确,配置看了没有问题115200-8-1-no,如何解决?
  • ¥15 Google speech command 数据集获取
  • ¥15 vue3+element-plus页面崩溃
  • ¥15 像这种代码要怎么跑起来?
  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误