简体   繁体   English

MySQL-在表1中创建表2中创建记录

[英]MySQL - Creating records in table 2 on creation in table 1

Say I have 2 tables, ballplayers and stats in my Database. 假设我的数据库中有2张桌子, 球手统计数据

when I add a ballplayers record (add someone new to the team) is there a way to create a new entry for that player in the stats table as well? 当我添加一个球员记录(向球队添加新人)时,是否也可以在统计表中为该球员创建一个新条目?

    ballplayers                           stats
 id, playername, number          id, totalpts, totalrebounds

(they are referenced using the id column in each table.) (它们在每个表中使用id列进行引用。)

So like this... Say I add to ballplayers 所以像这样...说我加入了球手

    ballplayers
 id, playername, number
  1    Nick        22

How can MySQL create a new entry in stats which is triggered on that entry creation in ballplayers with the given id and having defaults of totalpts and totalrebounds set to 0? MySQL如何在统计信息中创建一个新条目,该条目将在具有给定ID且将totalpts和totalrebounds的默认值设置为0的球员中创建该条目时触发?

    stats
 id, totalpts, totalrebounds
  1     0           0

Is this bad DB design? 这是不好的数据库设计吗? Is it possible without having to write two queries? 是否可以不必编写两个查询? ( INSERT INTO ballplayers; & INSERT INTO stats; )Any help would be appreciated. INSERT INTO ballplayers; & INSERT INTO stats; )任何帮助将不胜感激。

If you chose to go the route of a trigger, which would automatically add a row to the second table, you could do so using the following code: 如果选择使用触发器的路由,它将自动向第二个表添加一行,则可以使用以下代码:

create trigger trig_ballplayers_after_insert after insert on ballplayers
for each row insert ignore into stats values(new.id, 0, 0);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM