views:

36

answers:

2

I need some help with an insert statement.

I've got:

my_table_a:

School        Latitude     Longitude
Old School     38.6...     -90.990...
New School     38.6...     -90.990...
Other School   38.6...     -90.990...
Main School    38.6...     -90.990...

my_table_b:

School        Latitude     Longitude
City School
Old School
Central School        
New School    
Other School   

I need to insert the latitudes and longitudes from my_table_a into my_table_b where there is a match between the school names. The problem is that table A doesn't have all of table B's schools and vice versa.

I've tried a WHERE clause but it's not working. I need to insert where my_table_a.school = my_table_b.school . Any suggestions?

+1  A: 

Do you really want to insert or rather update?

What about

UPDATE my_table_b
set latitude = (select latitude from my_table_a where my_table_a.School = my_table_b.School),
    longitude = (select longitude from my_table_a where my_table_a.School = my_table_b.School)
where exists(select 1 from my_table_a where my_table_a.School = my_table_b.School)

This would be generic SQL. I am not sure if mysql supports an update of a join which would be a bit less repetitive and more efficient.

Frank
+1: Not all databases support JOINs in the UPDATE statement - this is the most portable version.
OMG Ponies
Hi Frank, Thanks so much. It worked perfectly. I was struggling with this problem for a couple of hours and you solved it in about 5 min. I learned something new about MySQL from you. Thanks.
Laxmidi
Hi OMG Ponies, Thank you for your message. As soon as I see your screen name pop up, I know that my problem will be solved soon. I think that you've posted on all of my mySQL problems-- and answered most of them. Thanks, again.
Laxmidi
+2  A: 

Using ANSI-92 syntax:

UPDATE TABLE_B
  JOIN TABLE_A ON TABLE_A.school = TABLE_B.school
  SET latitude = TABLE_A.latitude,
      longitude = TABLE_A.longitude

Using ANSI-89 syntax:

UPDATE TABLE_B, TABLE_A
  SET latitude = TABLE_A.latitude,
      longitude = TABLE_A.longitude
WHERE TABLE_A.school = TABLE_B.school
OMG Ponies