I'm working with a MySQL 5 db that uses 2 tables to store records - one records table that has a record ID for each submission and a subrecords table that contains name/value pairs for each of the elements and a record number linking them to the header record. This means that each record I want to display (for example, "Name, "Phone, "Address") is stored in multiple lines in the subrecords table with a matching record number that links them together.
I've been able to create a view that puts all related subrecords values into a single field by record number -
SELECT record, GROUP_CONCAT(value ORDER BY value separator ',') AS vals FROM subrecords GROUP BY record
This returns two columns, like -
Record vals
947 yes,Stage 1,St. Joseph,No Preference,,,,,,,,,,,,,,,,
,,,,Russel
l,Tripp,TE
STING,,TES
T,SC,29607
,888888888
8,work,JUS
TTESTING@a
vfcreation
s.com,larg
e,jklw;erj
io,8888888
888,Yes
Now I need a decent method of getting each of these values into a separate column from the view results, I've experimented some with using SUBSTRING_INDEX() and other string functions to get each value, but after you get past the first couple of values, my method for extracting becomes incredibly long and difficult to figure out what's going on - I feel certain there must be a better way to do this. There may or may not be values in each delimited field, but the number of fields is constant. Here's what I did to get the first few values successfully (the view above is named "build" here) -
SELECT
b.id AS RecordNum,
SUBSTRING_INDEX(b.vals,','
,1) AS ReadDesc,
SUBSTRING(SUBSTRING_INDEX(
b.vals,','
,2) FROM (LOCATE(',',SUBSTRING_INDE
X(b.vals,'
,',2))+1))
AS Stage1,
SUBSTRING(SUBSTRING_INDEX(
b.vals,','
,3) FROM (LOCATE(',',SUBSTRING_INDE
X(b.vals,'
,',3),( (LOCATE(',',SUBSTRING_INDE
X(b.vals,'
,',2))+1))
))+1) AS Stage1Loc,
SUBSTRING(SUBSTRING_INDEX(
b.vals,','
,4) FROM (LOCATE(',',SUBSTRING_INDE
X(b.vals,'
,',4),( (LOCATE(',',SUBSTRING_INDE
X(b.vals,'
,',4))+ LENGTH(SUBSTRING(SUBSTRING
_INDEX(b.v
als,',',3)
FROM (LOCATE(',',SUBSTRING_INDE
X(b.vals,'
,',3),( (LOCATE(',',SUBSTRING_INDE
X(b.vals,'
,',2))+1))
))+1))))))
+1) AS Stage1Pos
FROM build b
It works, but as you can see if I keep going to get additional records out, the lines in the select statement are going to be unbelievably long and, I'm sure, not very efficient. I need to find a way to do this in MySQL 5. Thanks.
Start Free Trial