当前位置: 首页 > 知识库问答 >
问题:

如何在行中插入外键?

夔建章
2023-03-14
--
-- Table structure for table `sector`
--

CREATE TABLE IF NOT EXISTS `sector` (
  `sector_id` int(11) NOT NULL AUTO_INCREMENT,
  `sector_name` varchar(100) NOT NULL,
  `sector_url` varchar(500) NOT NULL,
  PRIMARY KEY (`sector_id`),
  UNIQUE KEY `sector_id` (`sector_id`,`sector_name`,`sector_url`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


CREATE TABLE IF NOT EXISTS `constituent` (
  `constituent_id` int(11) NOT NULL AUTO_INCREMENT,
  `constituent_name` varchar(100) DEFAULT '',
  `constituent_ticker` varchar(10) NOT NULL,
  `constituent_isin_number` varchar(50) DEFAULT '',
  `constituent_currency` varchar(10) DEFAULT '',
  `sector_id` int(11) NOT NULL,
  PRIMARY KEY (`constituent_id`),
  KEY `sector_id` (`sector_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;


--
-- Constraints for table `constituent`
--
ALTER TABLE `constituent`
  ADD CONSTRAINT `constituent_ibfk_1` FOREIGN KEY (`sector_id`) REFERENCES `sector` (`sector_id`);
INSERT into constituent (constituent_name, constituent_ticker, constituent_isin_number, constituent_currency, sectorFK) 
values ("the name", "the ticker", "the number", "the currency", "the foreign key???")   

共有1个答案

公孙俭
2023-03-14

为了能够在插入到表b后获得主键值,为了将其插入到表a,可以使用last_insert_id()函数,在不带参数的情况下使用该函数,该函数返回为auto_increment列设置的最后一个自动生成的值:

例如:

insert into B(col)
  values(1);

insert into A(t1_id, col)
  values(last_insert_id(), 2);

insert into A(t1_id, col)
  values(last_insert_id(), 3);

SQLFIddle演示

 类似资料:
  • 问题内容: 我有本身具有外键的表。列 parentid 是外键, 不能 为NULL。 如果我这样做,那么它说不能将NULL插入 父母的父母 。但是,如果还没有插入行,我可以为它设置什么值呢? 我如何编写将向该表添加行的脚本? 谢谢 问题答案: 技巧:拥有一个带有虚拟密钥的虚拟行,例如99999。将其插入为FK,然后将FK更改为其实际值。并在交易中完成。

  • 问题内容: 我想进行批量插入事务,但是我不太确定如何使用CTE或更有效的方法来执行此操作。这是我到目前为止的内容: 我的CTE的问题是我不知道如何从要插入的第一条插入语句中获取单个ID到第二条具有“ product_id”外键的语句的相应记录中。 我将如何构造该语句以使其起作用?我对其他解决方案持开放态度,这些解决方案提供了更有效的方法来实现相同的结果。 问题答案: 以下是您要做什么的合理解释:

  • 问题内容: 我有一个列表,例如:thing1,thing2,thing3。我想将它们插入具有相同外键的查找表中。因此理想情况下,它看起来应该像这样: 看来完成此操作的唯一方法是将列表转换为查询,但是我想知道,是否有更简单的方法? 这是我尝试过的: 我听说您无法在cfquery中执行cfloop,但是我什至不确定这是否成立,因为VALUES中没有逗号,并且我不确定如何说“ cfloop中的“当前迭代

  • 我正在创建一个使用Apache Web服务器(PHPmyAdmin)的PHP网站 我有三张桌子: 品牌 brand_id(主键)自动增加 brand_name < li>item_id(主键)自动递增 < li >项目类别 model_id(主键)自动增加 item_model brand_id(brand.brand_id的外键) brand_name(item.item_id的外键) 数量 价

  • 问题内容: 我有许多记录需要输入到表中。在查询中执行此操作的最佳方法是什么?我是否应该进行循环并在每次迭代中插入一条记录?或者,还有更好的方法? 问题答案: 从MySQL手册 使用VALUES语法的INSERT语句可以插入多行。为此,请包括多个列值列表,每个列值括在括号内并用逗号分隔。例:

  • 问题内容: 在MySQL中,我会使用 但这会导致SQLite错误。SQLite的正确语法是什么? 问题答案: 在此之前,已经回答了这一问题:是否可以一次在SQLite数据库中插入多行? 要回答您对OMG Ponies的评论,请回答: 从3.7.11版本开始,SQLite确实支持多行插入。理查德·希普(Richard Hipp)评论: