title: MariaDB - GROUP BY with an order
body: <p>So I have a dataset, where I would like to order it based on strings <code>ORDER BY FIELD(field_name, ...)</code> after the order I wan't it to group the dataset based on another column.</p>
  
  <p>I have tried with a subquery, but it seems like it ignores by <code>ORDER BY</code> when it gets subqueried. </p>
  
  <p>This is the query I would like to group with <code>GROUP BY setting_id</code></p>
  
  <pre><code>SELECT *
  FROM `setting_values`
  WHERE ((`owned_by_type` = 'App\\Models\\Utecca\\User' AND `owned_by_id` = 1 OR ((`owned_by_type` = 'App\\Models\\Utecca\\Agreement' AND `owned_by_id` = 1006))) OR (`owned_by_type` = 'App\\Models\\Utecca\\Employee' AND `owned_by_id` = 1)) AND `setting_values`.`deleted_at` IS NULL
  ORDER BY FIELD(owned_by_type, 'App\\Models\\Utecca\\Employee', 'App\\Models\\Utecca\\Agreement', 'App\\Models\\Utecca\\User')
  </code></pre>
  
  <p>The order by works just fine, but I cannot get it to group it based on my order, it always selects the one with lowest primary key (id).</p>
  
  <p>Here is my attempt which did not work.</p>
  
  <pre><code>SELECT * FROM (
      SELECT *
      FROM `setting_values`
      WHERE ((`owned_by_type` = 'App\\Models\\Utecca\\User' AND `owned_by_id` = 1 OR ((`owned_by_type` = 'App\\Models\\Utecca\\Agreement' AND `owned_by_id` = 1006))) OR (`owned_by_type` = 'App\\Models\\Utecca\\Employee' AND `owned_by_id` = 1)) AND `setting_values`.`deleted_at` IS NULL
      ORDER BY FIELD(owned_by_type, 'App\\Models\\Utecca\\Employee', 'App\\Models\\Utecca\\Agreement', 'App\\Models\\Utecca\\User')
  ) AS t
  GROUP BY setting_id;
  </code></pre>
  
  <p>Here is some sample data
  <a href="https://i.stack.imgur.com/mM3eX.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mM3eX.png" alt="enter image description here"></a></p>
  
  <p>What I am trying to accomplish with this sample data is 1 row with the id 3 as the row. <br>
  The desired result set from the query should obey these rules</p>
  
  <ul>
  <li>1 row for each <code>setting_id</code></li>
  <li><code>owned_by_type</code> together with <code>owned_by_id</code> is filtered the following way <code>agreement = 1006</code>, <code>user = 1</code>, <code>employee = 1</code>.</li>
  <li>When limiting the 1 row for each <code>setting_id</code>it should be done with the following priority in <code>owned_by_type</code> column <code>Employee, Agreement, User</code></li>
  </ul>
  
  <p>Here is a <a href="http://sqlfiddle.com/#!9/565110/5" rel="nofollow noreferrer">SQLFiddle</a> with it.</p>
  
  <p>Running MariaDB version 10.2.6-MariaDB</p>