tags:

views:

34

answers:

2
+1  Q: 

UPDATE REGEX MYSQL

I have a table of contacts and a table of postcode data.

I need to match the first part of the postcode and the join that with the postcode table... and then perform an update...

I want to do something like this...

UPDATE `contacts` LEFT JOIN `postcodes` ON PREG_GREP("/^[A-Z]{1,2}[0-9][0-9A-Z]{0,1}/", `contacts`.`postcode`) = `postcodes`.`postcode` SET `contacts`.`lat` = `postcode`.`lat`, `contacts`.`lng` = `postcode`.`lng`

Is it possible?? Or do I need to use an external script?

Many thanks.

A: 

Im not sure what you are using the regex for but if you just need the first [LENGTH] characters to be the same this will work:

update c
set c.lat = p.lat, c.lng = p.lng
from contacts c
inner join postcodes p
  on substring(c.postcode, 0, [LENGTH]) = substring(p.postcode, 0, [LENGTH]
Fabian
The contacts table has the full postcode eg "W1A 1AA" and the postcode table only has "W1A"... The trouble is the data is inconsistent so might be written as "W1A1AA" or "w1A1aA".
Simon
It seems that mysql doesnt support capturing like that so if you want it perfect you are going to have to create a script :/
Fabian
A: 

I decided to approach it from a different angle... there might be a few clashes but I can live with that.

UPDATE fellow f INNER JOIN postcode p ON f.postcode LIKE CONCAT(p.postcode, "%") SET f.lat = p.lat, f.lng = p.lng
Simon
Unless you change the LEFT OUTER JOIN to an INNER JOIN or add a WHERE clause, you've just updated all of the records in the fellow table, some of them possibly to null values. Is that your intention?
Marcus Adams
Good point. Just edited...
Simon