views:

60

answers:

2

I have a table called cartypes which currently has 2 fields: id & type. I am adding subtype and I want to move the contents after the dash - from the field called type and put those contents into subtype. Disposing of the dash (any extra whitespace too for that matter). What's the best SQL query for this?

before:

id        type                                      subtype (currently empty)
------------------------------------------------------------------------------
1     legendary muscle car  - steel          
2     crappy sedan - plasticky interior
3     legendary sports car  - aluminum bodywork
4     compact car

after:

id        type                     subtype
---------------------------------------------------------------
1     legendary muscle car        steel          
2     crappy sedan                plasticky interior
3     legendary sports car        aluminum bodywork
4     compact car
+1  A: 

That's an update statement involving two SUBSTR() (one for each new column) and a string LOCATE() on the original column. I don't really use MySQL much, but this trick works everywhere, just the syntax of the string finding routines changes.

Norman
Here's a link to a similar type question with some syntax: http://stackoverflow.com/questions/993205/mysql-substring
quickcel
Hmm, so then I need to do the update while looping a select like the following? SELECT CASE WHEN LOCATE('-',type) = 0 THEN '' ELSE SUBSTRING(type,LOCATE('-',type)+1) END as subtype FROM cardsBut that will still leave the now unwanted stuff in the orig type col, no?
k00k
+1  A: 
UPDATE table
 SET subtype = TRIM(SUBSTRING(type, LOCATE('-', type) + 1)),
     type = TRIM(SUBSTRING(type, 1, LOCATE('-', type) - 1))
 WHERE type LIKE '%-%';
Keith Randall
Thanks Keith, I tried it and that's close. The problem I think I'm having with that is that you SET type to it's new value before you SET subtype. So subtype becomes NULL.
k00k
So I just swapped the 2 SETs, setting subtype first and that works, however the value of type now ends with the dash. eg: crappy sedan -
k00k
Not a big deal, just did a search and replace for '\ -' (backslash space dash) and replaced it with nothing. All good. Thanks!
k00k
Off-by-one error. Stupid sql having indexes start at 1... You just need LOCATE('-', type) - 1 as the argument in the first SUBSTRING (or after reordering, the second one).
Keith Randall