如何更新其他相关表中的PRIMARY KEY / FOREIGN KEY? [英] How to update the PRIMARY KEY/FOREIGN KEY in other related tables?

查看:162
本文介绍了如何更新其他相关表中的PRIMARY KEY / FOREIGN KEY?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

墙壁


  • wall_id(P)

  • wall_name

  • wall_views

  • wall_downloads

  • wall_thumbnail_path


4,'wall4','125','574','../.../ thumbnail_wall4.jpg'



类型


  • type_id

  • type_name


'1','桌面'
' 2','Phone'
'3','平板电脑'


$ b (P)(F)
  • type_id(P)


    • wall_id (F)


    4,1



    以上是我拥有的表格,我想要做的是从 walls自动获取 wall_id = 4 / code>表,并将其存储在 wall_types 表中,与中的 type_id 相同>类型表。如何才能做到这一点?什么是代码(PHP代码)或SQL语句来实现这一目标?谢谢!



    注意:


    • wall_types 引用 wall_id

    • type_id in types 在类型表中引用 type_id


    • 解决方案

      下面的查询在你的wall_types表中插入一个新的关系,其中'1'来自用户输入(用户选择桌面): / p>

        INSERT INTO wall_types(wall_id,type_id)VALUES(5,1); 

      如果您想在插入新的墙 off)当然还不清楚,你可以使用LAST_INSERT_ID(),这将包含最后插入的id,因此你需要在'wall'插入查询之后执行这个查询:

        INSERT INTO wall_types(wall_id,type_id)VALUES(LAST_INSERT_ID(),1); 


      walls

      • wall_id (P)
      • wall_name
      • wall_views
      • wall_downloads
      • wall_thumbnail_path

      (4, 'wall4', '125', '574', '../.../thumbnail_wall4.jpg')

      types

      • type_id
      • type_name

      ('1', 'Desktop') ('2', 'Phone') ('3', 'Tablet')

      wall_types

      • wall_id (P) (F)
      • type_id (P) (F)

      (4, 1)

      Above are the tables I have, what I want to do is automatically get the wall_id = 4 from walls tables and store it in wall_types table, same with the type_id from types table. How can this be done? what is the code (PHP code) or SQL statements to achieve this? thanks!

      Note:

      • wall_id in wall_types references wall_id in walls table.

      • type_id in types references type_id in types table.

      解决方案

      The query below inserts a new relation in your wall_types table, where '1' comes from user input (user selected 'Desktop'):

      INSERT INTO wall_types (wall_id, type_id) VALUES (5,1);
      

      If you want to do this right after you inserted a new 'wall' row where the id is (off course) unknown yet, you can use LAST_INSERT_ID(), this will contain the last inserted id, therefore you need to execute this query right after the 'wall' insert query:

      INSERT INTO wall_types (wall_id, type_id) VALUES (LAST_INSERT_ID(),1);
      

      这篇关于如何更新其他相关表中的PRIMARY KEY / FOREIGN KEY?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆