Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>In order to get the data into your columns, you can use an aggregate function with a <code>CASE</code> expression to convert the row data into columns.</p> <p>If your <code>fields</code> are known ahead of time, then you can hard-code the values in your query:</p> <pre><code>select u.id, u.username, max(case when f.name = 'firstname' then uf.value end) firstname, max(case when f.name = 'lastname' then uf.value end) lastname from user u left join ( select uf1.* from user_fields uf1 inner join ( select max(date) maxDate, user_id, fields_id from user_fields group by user_id, fields_id ) uf2 on uf1.date = uf2.maxdate and uf1.user_id = uf2.user_id and uf1.fields_id = uf2.fields_id ) uf on u.id = uf.user_id left join fields f on uf.fields_id = f.id group by u.id, u.username; </code></pre> <p>See <a href="http://www.sqlfiddle.com/#!2/43822/8" rel="nofollow">SQL Fiddle with Demo</a></p> <p>But since you are going to have unknown fields, then you will need to use a <a href="http://buysql.com/mysql/14-how-to-automate-pivot-tables.html" rel="nofollow">prepared statement</a> to generate dynamic SQL to execute. The syntax will be similar to this:</p> <pre><code>SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(CASE WHEN f.name = ''', name, ''' THEN uf.value END) AS `', name, '`' ) ) INTO @sql FROM fields; SET @sql = CONCAT('SELECT u.id, u.username, ', @sql, ' from user u left join ( select uf1.* from user_fields uf1 inner join ( select max(date) maxDate, user_id, fields_id from user_fields group by user_id, fields_id ) uf2 on uf1.date = uf2.maxdate and uf1.user_id = uf2.user_id and uf1.fields_id = uf2.fields_id ) uf on u.id = uf.user_id left join fields f on uf.fields_id = f.id group by u.id, u.username'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; </code></pre> <p>See <a href="http://www.sqlfiddle.com/#!2/43822/9" rel="nofollow">SQL Fiddle with Demo</a></p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload