I have a table, called pat_authors with 2 columns- last_name, first_initials
I want to select distinct combinations of the two columns. The following command works to retrieve the correct information:
select distinct last_name, first_initials from pat_authors;
However, I want to retrieve the same information and then insert it into another table, called unique_authors, where unique_authors has 3 columns – authorID,last_name,first_initials.
I’ve tried so many variations of code, I’m going crazy. Here are what I considered to be my 2 closest to being correct attempts:
select distinct author_last_name, author_initials into uniqueauthors from pat_authors;
Which gave me an error – 1327:undeclared variable: uniqueauthors
I’ve also tried
insert into uniqueauthors select distinct author_last_name, author_initials from pat_authors;
Which gives me Error Code: 1136. Column count doesn't match value count at row 1. Here I thought I’d be fine because my authorID column is NOT NULL AUTO_INCREMENT
The reason it’s not working is because the
INSERTstatement wouldn’t know which two columns to insert data into from the two columns in theSELECT. You need to either explicitly specify the columns you’re going toINSERTinto:Or you can leave the column specification implicit. However, if you do that, you’ll need to make sure there are an equal number of columns (in matching order) in the
SELECTas there are columns in the table definition (even including the auto-incrementing column). How do can you still have the column auto-increment? You can simply specifyNULLas the first column in theSELECT:Useful tip: whenever you try to insert a
NULLvalue into a auto-incrementing column, it will simply insert the auto-incremented value instead.