我目前有以下查询,我想用它来插入两个字符串和一个外键。但是,当我传递外键的字符串时,我想在插入时获取键,因此记录实际上将读取为:
《全亚洲资产 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;