0

This is my first post here.

My question is similar to a previous thread albeit different: mysql converting multiple rows into columns in a single row

What I have is really a large form. There are many forms (sheets, really) and each has the same setup. Each form has labels and values, but the values in the forms can be changed and the forms only display the ''latest'' values. The database has a few tables but those important here are the field_labels and the field_values. These two are linked as one might suspect and, the field_value table has a ''date'' column.

Now, what I wan't to do is to select the field_label.id, and the latest value (field_value.fv_value). First I thought this might work fine with CASE but the problem is, CASE stops searching the table immediately after it finds a hit that matches, I want to select the latest hit, not just the first one matched.

The only good idea I had so far is to use a subquery and reform the value table by ordering it first by the (linked) id of the labels, and then by the ''date'' of the value. Here's what I got

SELECT T.msdsid,
       field_label.id,
       (CASE WHEN field_label.id = 1 THEN T.fv_value ELSE NULL END) AS value
FROM (SELECT * FROM field_value ORDER BY field_value.fl_id,field_value.date DESC) AS T
LEFT JOIN field_label ON(T.fl_id=field_label.id)
GROUP BY T.refid;

Now, this does do exactly what I want, but... is there a better way?

Thanks in advance.

Community
  • 1
  • 1

1 Answers1

1

This query will show you the latest values (record) for each field_value.fl_id:

SELECT fv1.* FROM field_value fv1
  JOIN (SELECT fl_id, MAX(date) date FROM field_value GROUP BY fl_id) fv2
    ON fv1.fl_id = fv2.fl_id AND fv1.date = fv2.date;

Try this query, play with it, and add it into your query.

Devart
  • 119,203
  • 23
  • 166
  • 186