Insert without specifying columns

Asked

Viewed 1,509 times

1

I have several tables T1, T2... TN, each one can have columns in common or not. My final table F, contains all the columns (one time) of the previous ones.

There is how I insert from each without having to explain which columns I am inserting?

For example, let’s say that table T1 has columns A and B. Table F has A, B, C and D.

I’d like something like

insert into F select * FROM T1;

or

insert into F select A,B,C,D FROM T1;

1 answer

0


No. Cannot INSERT without defining columns. When you use

INSERT INTO tabela VALUES(a, b, c) 

you are implicitly saying that you will use ALL columns in the order in which they were created.

But you can use it to do things like:

INSERT INTO a SELECT a, null, 'X' FROM  b WHERE condicao 

provided that your columns accept NULL value and that a value passed as default for each row can accept 'X' as value.

A more practical example to understand: Assuming B = (id_A, tp_Sangue, factor_RH) and A = (id_A, NAME, SEX)

INSERT INTO B SELECT id_A, 'AB', 'RH+' FROM A WHERE SEXO='F';

We will be assigning 'AB' and 'RH+' to all records with SEX = 'F';

Another way to do something like you explained about INSERT INTO F SELECT * FROM T1; would create a VIEW containing fields equal to F from T1;

  • Okay, thank you. I thought that just as there is natural JOIN, there could be a "natural INSERT" by inserting the columns according to their names.

  • MYSQL Suport a different type of INSERT that uses SYNTAX INSERT INTO tabela SET campo1 = {expressao}, campo2 ={expressao}...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.