0

I have two tables with similar column values for columns "name" and "regis". One table is already filled with values, the other has only values for "name". How do i get "regis" values from table1 into table2 based on same column values?

I tried something like this

INSERT INTO table2 (regis)
SELECT table1 (regis)
WHERE table2.name = table1.name
2
  • Please tag database. Your question is bit ambiguous. Do you want to update the regis column with matching values on name? or insert again if name match is found? Commented Jun 17, 2022 at 12:55
  • MySQL: update table2 t2 inner join table1 t1 on t2.name = t1.name set t2.regis = t1.regis; Commented Jun 17, 2022 at 13:46

3 Answers 3

1

Please try:

update table2 set regis = (select regis from table1 where table1.name=table2.name);

see the whole sample on: https://www.db-fiddle.com/f/3jC8PGeZZEuty3XVq8gdzz/9

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

2 Comments

thanks i tried this but there is an error: error-1242-subquery-returns-more-than-1-row
are there duplicate rows with the same "name"? If so, how to get the same value of "regis"? try this: update table2 set regis = (select regis from table1 where table1.name=table2.name limit 1);
1

I think, what you are after is insert when name not found in table2 or update if its found in both tables.

INSERT INTO TABLE2 (regis)
SELECT t1.REGIS FROM TABLE1 as t1
LEFT OUTER JOIN TABLE2 as t2 on t2.name = t1.name
WHERE t2.name is null

You can update table2 using the statement like below:

update t2
   set t2.regis = t1.regis
from table2 as t2
inner join table1 as t1 on t1.name = t2.name

If you are using SQL Server, then you can use merge statement to either insert or update in one step.

4 Comments

i dont understand the syntax, what is t2 and t1?
t2 and t1 are the aliases.
unfortunately, the insert statement doesnt work. i get error #1052 1052: Column 'regis' in field list is ambiguous. the update statement has wrong syntax error #1064
Updated my insert statement which now says take table1 regis.
-1

You need to use table2 as join in your select statement.

INSERT INTO table2 (regis)
SELECT table1.regis FROM Table1 INNER JOIN Table2 on table1.name = table2.name

2 Comments

i tried this but it removed all table2.name values. any fix?
it should not be, paste your query

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.