views:

123

answers:

3

Hi

I have a table with a field where words are written separated with new lines. So a select on this single field from to rows will output 3 lines for first row and 2 lines for second row:

Row1    designationer
        nye kolonier
        mindre byer
Row2    udsteder
        bopladser

I would like to do a select that select all these lines as if they had been rows in the table like:

SELECT do_the_split(field) FROM table

so the result would be more like:

Row1    designationer
Row2    nye kolonier
Row3    mindre byer
Row4    udsteder
Row5    bopladser

is there any way to do this in MySQL?

BR. Anders

UPDATE: There are correct answers below but ended up doing it in a semi-manual way. I did this:

  1. exporting the the column to a csv
  2. Open file in notepad and remove the pings around each line
  3. now each word is on a new line
  4. save as csv
  5. import into database where each line will be a new row

Br. Anders

A: 

I don't know the in-and-outs of mySQL to be of any help in that but what's stopping you from doing the splitting in the application layer? Say, you load your rows, as they are, in Java (or PHP or whatever) and then

String row = <fetch row from resultset>;
String[] individualItems = row.split("\n");

If you could store the values like that in your DB, you could just as well retrieve them like that.

Peter Perháč
Hi Peter. Yep, it is indeed possible to do in a scripting language. I am not in a hurry with this assignment and use it to dive into more complex mysql commands. Until now I have only done select, update, append, delete but no combinations of them. So just trying to learn :-) But thanks for feedback
Tillebeck
oh, okay, i see. good luck then!
Peter Perháč
+1  A: 

I've faced the same problem and the only two ways I know of getting the kind of collection of words you want are stored procedures (which is what I did, although with the Derby DB) or a script/program.

Tomislav Nakic-Alfirevic
precisely. those are the right choices. although i feel there might be a SQL way of doing this but this will be dependent on the dialect used by the particular DBMS vendor.
Peter Perháč
What it comes down to is that storing information in a DB like that is usually (always?) just plain wrong: the simplest single, atomic unit of information is supposed to be a field of a record. If you violate that, a relational database will basically give up and leave everything up to you.
Tomislav Nakic-Alfirevic
I agree, totally. It is a system that someone else build and I shall take over the service on. I will make a proper database structure before building a new frontend. There are many more "issues" just like this one and all have to be fixed before doing further development.
Tillebeck
+2  A: 

You can use a stored procedure - similar to what this person did - to accomplish this, essentially utilizing a temp table.

Certainly you could accomplish this locally in your app, as MasterPeter has suggested.

itsmatt