Insert mysql on foreign key id php

和自甴很熟 提交于 2019-12-11 07:08:33

问题


I have 2 tables, clubs and fixtures

clubs

id (int)
name (text)

fixtures

id (int)
hometeam (int, foreign key to clubs id)
awayteam (int, foreign key to clubs id)
datetime (datetime)

Each fixtures record uses an ID for the hometeam and awayteam as per the foreign key relationship.

I need to do an insert into the fixtures table, but I only have the hometeam name not the hometeam id. Is there a way of doing this through the foreign key relationship, without having to separately lookup the relevant id number?


回答1:


There is nothing wrong with looking for foreign key value through a separate select query:

INSERT INTO `fixtures`
    VALUES ( NULL,
             (SELECT `id` FROM `clubs` WHERE `name` = 'NAME'),
             AWAYTEAM_ID,
             CURRENT_TIMESTAMP
    );



回答2:


You need to do in 2 steps:

  • Insert hometeam in clubs table (get hometeamID if already have, otherwise insert and get ID)
  • Then insert into fixtures table


来源:https://stackoverflow.com/questions/50795607/insert-mysql-on-foreign-key-id-php

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