2

I came across a scenario where I need to "upgrade" a table with data I obtain from another query. I am adding missing values so I will need to insert, but I cant seem to get it right.

The destination table is the following

CREATE TABLE `documentcounters` (
  `UID` int,
  `DataChar`,
  `SeqNum` ,
  `LastSignature`,
  `DocumentType`,
  `SalesTerminal`,
  `Active`,
  PRIMARY KEY (`UID`)
) ENGINE=InnoDB 

and I am trying to do something like

INSERT INTO documentcounters
SELECT Q1.in_headers, -1,NULL, 17,0,0 FROM 
    (SELECT DISTINCT(DocumentSeries) as in_headers  FROM transactionsheaders )AS Q1
    LEFT JOIN 
    (SELECT DISTINCT(DataChar) as in_counters FROM documentcounters)AS Q2
ON Q1.in_headers=Q2.in_counters WHERE Q2.in_counters IS NULL;

I left UID out because I want the insert statement to create it, but I get a "Column count doesn't match" which makes sense (darn!)

Doing something like

INSERT INTO `documentcounters`
(`DataChar`,`SeqNum`,`LastSignature`,`DocumentType`,`SalesTerminal`,`Active`)
VALUES
(
(SELECT Q1.in_headers FROM 
    (SELECT DISTINCT(DocumentSeries) as in_headers  FROM transactionsheaders )AS Q1
    LEFT JOIN 
    (SELECT DISTINCT(DataChar) as in_counters FROM documentcounters)AS Q2
ON Q1.in_headers=Q2.in_counters WHERE Q2.in_counters IS NULL),-1,NULL,17,0,0
);

yields a "Subquery returns more than 1 row" error.

Any ideas how I can make this work?

Cheers

2
  • if you run the sub queries separate do they only return 1 record? Commented Jan 17, 2012 at 16:03
  • @Robert. No, I can have more than one record Commented Jan 17, 2012 at 16:04

2 Answers 2

2
INSERT INTO `documentcounters`
(`DataChar`,`SeqNum`,`LastSignature`,`DocumentType`,`SalesTerminal`,`Active`)
SELECT Q1.in_headers, -1,NULL, 17,0,0 FROM 
    (SELECT DISTINCT(DocumentSeries) as in_headers  FROM transactionsheaders )AS Q1
    LEFT JOIN 
    (SELECT DISTINCT(DataChar) as in_counters FROM documentcounters)AS Q2
ON Q1.in_headers=Q2.in_counters WHERE Q2.in_counters IS NULL;

This will work if UID is defined as auto_increment.

Sign up to request clarification or add additional context in comments.

1 Comment

just remove Values and that's it?!
1

If you want the INSERT to create the UID values, then UID must be defined as an auto-incrementing column.

CREATE TABLE `documentcounters` (
  `UID` INT NOT NULL AUTO_INCREMENT,
   ...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.