简体   繁体   English

SQL:列数不匹配

[英]SQL: Column count does not match

I'm trying to insert values from two tables into a new table, but I keep getting the 'column count does not match' when it does.我正在尝试将两个表中的值插入到一个新表中,但是当它发生时我一直收到“列数不匹配”。 This is what I have so far:这是我到目前为止:

create table contribution (
  contb_id      integer primary key auto_increment,
  cand_id       varchar(12),            
  contbr_id     varchar(12),            
  amount        numeric(8,2),           
  date          varchar(20),            
  election_type varchar(20),            
  tran_id       varchar(20),            
  foreign key (cand_id) references candidate,
  foreign key (contbr_id) references contributor
);

and to insert the values into it:并将值插入其中:

INSERT INTO contribution (cand_id, contbr_id, amount, date, election_type, tran_id)
SELECT (cand_id, cb.contbr_id, contb_receipt_amt, contb_receipt_dt, election_tp, tran_id) 
FROM campaign, contributor cb

Any help would be greatly appreciated!任何帮助将不胜感激!

Essentially the answer is here: https://stackoverflow.com/a/5391390/12672179基本上答案在这里: https : //stackoverflow.com/a/5391390/12672179

For your case when you are inserting using select you should NOT have the brackets.对于您使用 select 插入的情况,您不应该使用括号。 Brackets in a select statement act very funky and essentially is making each column combine into 1 in its view. select 语句中的括号非常时髦,本质上是使每个列在其视图中合并为 1。 So to fix the column count issue in your INSERT statement just do this因此,要解决 INSERT 语句中的列数问题,请执行以下操作

  INSERT INTO contribution (cand_id, contbr_id, amount, date, election_type, tran_id)
      SELECT cand_id, cb.contbr_id, contb_receipt_amt, contb_receipt_dt, election_tp, tran_id 
  FROM campaign, contributor cb

Additionally this is still wrong as you cannot do two from tables in the same FROM instead you should JOIN the second table ON a value where the two tables match (In other words the foreign key field).此外这还是错了,因为你不能在同一个表FROM而不是你应该加入第二个表哪里两个表匹配(换句话说,外键字段)的值,做两。 I'm not going to tell you which type of JOIN to use as that depends on your data and if every single value has a link or not.我不会告诉您使用哪种类型的 JOIN,因为这取决于您的数据以及每个值是否都有链接。

Finally you should also include a WHERE so sql knows which values to fetch if you only want to do specific and not all.最后,您还应该包含一个WHERE,以便 sql 知道要获取哪些值,如果您只想执行特定操作而不是全部操作。

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

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