繁体   English   中英

将值插入到引用另一个表的MySQL表中以获取外键

[英]Insertion of values into a MySQL table referencing another table for a foreign key

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

“所有亚洲资产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"))

试试这个查询..

    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

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

//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);

}

未知列的问题似乎已经解决,方法是用单引号将列名引起来,以便该行现在显示为:

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

不好意思

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

我是个白痴。

不过谢谢

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM