0

I am trying to insert values from table2 to table1 where addressB matches addressA. My attempt so far is the code below. The query seems to insert new blank records to the table1 instead what I want it to do. Can someone please tell me if this query is correct?

INSERT INTO database1.table1 (name)
select database2.table2.distName
from database2.table2
left join database1.table1
On database2.table2.addressB = database1.table1.addressA
where database2.table2.addressB = database1.table1.addressA

My sql fiddle

http://sqlfiddle.com/#!9/aca3e/2
5
  • I do not really understand what you would like to achieve! 1. There is no point in using a left join and then repeat the join condition in where as well. Use an inner join instead. 2. If the address already exists in table1, then why do you insert a record instead of updating it? 3. Are you sure that a_distName2 field is populated in table2?
    – Shadow
    Commented Feb 12, 2016 at 9:28
  • I repeated the where condition as the join was not giving the correct result. I get the exact results I want when I use only the select part of the query. Yes distName field exists in table2 Commented Feb 12, 2016 at 9:42
  • If the select part alone produces the expected outcome, then the problem is with the insert part, but we would have to see the target table structure and some sample data from both tables.
    – Shadow
    Commented Feb 12, 2016 at 9:46
  • I will create sql fiddle example Commented Feb 12, 2016 at 9:55
  • sqlfiddle.com/#!9/aca3e/2 Commented Feb 12, 2016 at 10:51

3 Answers 3

2
INSERT INTO database1.table1 (name)
select database2.table2.a_distName2
from database2.table2
left join database1.table1
On database2.table2.addressB = database1.table1.addressA
where database1.table1.addressA is null;
1
  • where database1.table1.addressA is null; can be avoid if you will use inner join Commented Feb 12, 2016 at 9:30
1

After the sql fiddle I'm even more convinced that you need to use update and not insert.

update table1 inner join table2 on table1.addressA=table2.addressB
set table1.distname=table2.distname

The null values in the table1.id columns after your insert are the result of lacking a primary key on table1.id and lacking of the auto_increment specification on the same column.

1
  • Thanks for taking time to understand my problem. I was mixing up insert for update. Your query works Commented Feb 12, 2016 at 11:40
0
INSERT INTO database1.table1 (name)
select database2.table2.a_distName2
from database2.table2
inner join database1.table1
On database2.table2.addressB = database1.table1.addressA

Not the answer you're looking for? Browse other questions tagged or ask your own question.