0

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

《全亚洲资产 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;
4

5 回答 5

0

而不是sector.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"))
于 2013-09-14T09:52:52.907 回答
0

试试这个查询..

    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"))

SQLFiddle

于 2013-09-14T10:31:17.057 回答
0

您使用的方式不是插入使用executeUpdate()的方式

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

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

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

}
于 2013-09-14T10:34:53.960 回答
0

未知列问题似乎已通过用单引号括住列名来解决,因此该行现在显示为:

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"))
于 2013-09-15T06:16:37.140 回答
0

对不起大家。

未知列是因为应用程序指向没有该列的正确数据库,并且我试图通过 PHPMyAdmin 手动插入到具有该列的不正确数据库中。

我是个白痴。

不过谢谢。

于 2013-09-15T14:54:41.757 回答