How to update the PRIMARY KEY/FOREIGN KEY in other related tables?

我与影子孤独终老i 提交于 2020-02-07 06:00:06

问题


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.


回答1:


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);



回答2:


If you want to do this "automatically" you can use Triggers to update the relashionship. The other way is remove the relationship in wall_types and re-create with the updated values.



来源:https://stackoverflow.com/questions/19659979/how-to-update-the-primary-key-foreign-key-in-other-related-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!