mysql 外键关联用id,MySQL外键关系vs mysql_insert_id来关联表

This is for a sort of proof of concept draft to get things working, but don't want to have completely crap code. For my database, I tried to get true foreign key relations going using innoDB, but couldn't get it.

Instead of using foreign keys, I decided to just pull mysql_insert_id() after inserts, saving it as a variable, then putting that variable into the related table.

Is this horrible? Everything seems to work well, and I'm able to connect and relate ID's as needed. What benefits would using foreign keys give me over my method (besides updates/deletes cascading)?

解决方案

To create a relation (master->detail), you have to always supply the keys by yourself, either using mysql_insert_id, natural keys or key generated by your applications. The FOREIGN KEY is not going to make that work for you.

What FOREIGN KEY does is

Helping you enforce the relationship/the integrity of your data (so the "detail" record does not point to an invalid parent)

Handles deletion or key alterations of master records (ON DELETE ..., ON UPDATE ...).

It's also creating an index in your "detail"-table for the "master_id"-row if it doesn't exist yet (okay, you could also do that without FOREIGN KEY)

Has also some kind of documenting purpose for example an ERM-tool could reengineer the relationship model from your schema (okay, this point is a slight long shot)

The cost of adding the FOREIGN KEY constraint statement is small compared to its benefits.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
MySQL 中,可以使用 SUBSTRING() 函数来切割字符串,并将切割出来的字段作为外键关联其他。下面是一个示例: 假设有两个,一个是 orders ,包含订单信息;另一个是 customers ,包含客户信息。orders 中有一个字段 customer_info 存储客户信息,格式为 "姓名-电话号码"。现在需要将 customer_info 字段切割成姓名和电话号码两个字段,并将姓名作为 orders 外键关联 customers 。 首先,在 customers 中创建一个自增的 id 字段作为主键: ``` CREATE TABLE customers ( id INT NOT NULL AUTO_INCREMENT, name VARCHAR(50), phone VARCHAR(20), PRIMARY KEY (id) ); ``` 然后,在 orders 中添加一个外键字段 customer_id,用于关联 customers 的主键 id: ``` ALTER TABLE orders ADD COLUMN customer_id INT; ``` 接着,使用 SUBSTRING() 函数将 customer_info 字段切割成姓名和电话号码两个字段,并将姓名插入 customers 中: ``` INSERT INTO customers (name, phone) SELECT SUBSTRING(customer_info, 1, INSTR(customer_info, '-')-1), SUBSTRING(customer_info, INSTR(customer_info, '-')+1) FROM orders; ``` 最后,使用 UPDATE 和 INNER JOIN 语句将 orders 中的 customer_id 字段更新为 customers 中对应的 id 值: ``` UPDATE orders o INNER JOIN customers c ON SUBSTRING(o.customer_info, 1, INSTR(o.customer_info, '-')-1) = c.name SET o.customer_id = c.id; ``` 这样就完成了将切割出来的字段作为外键关联其他的操作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值