gpt4 book ai didi

java - 将值插入到引用另一个表的外键的 MySQL 表中

转载 作者:行者123 更新时间:2023-11-30 01:18:38 25 4
gpt4 key购买 nike

我目前有以下查询,我想用它来插入两个字符串和一个外键。但是,当我传递外键的字符串时,我想在插入时获取 key ,以便记录实际上读取为:

“全亚洲 Assets Cp”、“AAA”、1

下面是我使用的字符串:

    String sql = "INSERT into constituent " + 
"(constituent_name, constituent_ticker, sector_id) values (\""+
constituent.getConstituentName() + "\",\"" +
constituent.getConstituentTicker() + "\"," +
"(select id from sector where sector_name = \"" + constituent.getConstituentSector() + "\"))";

下面是查询。

INSERT into constituent (constituent_name, constituent_ticker, sector_id) 
values ("All Asia Asset Cp","AAA",
(select sector.id from sector where sector_name = "General Financial Sector"))

但是,我收到以下错误,我很困惑。有什么想法吗?

Unknown column 'sector.id' in 'field list'

按原样在 phpMyAdmin 中运行查询是可行的。

使用以下代码从 java 运行它会引发错误:

    //Initialize insertValues
insertValues = connect.prepareStatement(sql);

//Attempt to add the values into the database
try {
insertValues.execute();
} catch (Exception e) {

Log.e(CLASS_NAME, "createConstituent ", e);

}

扇区表的DDL:

CREATE TABLE `sector` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`sector_name` varchar(100) DEFAULT NULL,
`sector_url` varchar(500) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=latin1;

对于成分表的DDL:

CREATE TABLE `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 AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

最佳答案

您可以尝试仅使用 id 来代替扇区.id 吗?可以吗?

INSERT into constituent (constituent_name, constituent_ticker, sector_id) values ("All Asia Asset Cp","AAA",(select id from sector where sector_name = "General Financial Sector"))

关于java - 将值插入到引用另一个表的外键的 MySQL 表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18800401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com