Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You need an <a href="https://stackoverflow.com/questions/38549/sql-difference-between-inner-and-outer-join">outer join</a>.</p> <p>If you don't care about the order in which the "won" trophies appear, you could very simply do the following (because <code>winner_id</code> will be <code>NULL</code> for those trophies that have not been won and <a href="http://dev.mysql.com/doc/refman/5.5/en/working-with-null.html" rel="nofollow noreferrer"><code>NULL</code> is ordered "after" all other results in a descending order</a>):</p> <pre><code>SELECT * FROM trophies_list NATURAL LEFT JOIN trophies_won ORDER BY winner_id DESC, RAND(); </code></pre> <p>Of course, if when you said that "all trophies that have not been won should be in a random order" you meant you merely didn't care about the order, you can omit the trailing "<code>, RAND()</code>".</p> <hr> <p><strong>UPDATE</strong></p> <p>In response to your comments, I think you're actually looking for something more like:</p> <pre><code>SELECT trophies_list.*, NOT ISNULL(trophies_won.winner_id) AS won FROM trophies_list LEFT JOIN trophies_won ON ( trophies_won.trophy_id = trophies_list.trophy_id AND trophies_won.winner_id = 43 ) ORDER BY won DESC, RAND(); </code></pre> <p>By performing an outer join <code>ON</code> the criteria you're after, you can identify amongst the list of all trophies which match that criteria and which don't. In this case, which trophies have been won by the specified winner and which haven't.</p> <p>The <code>ORDER BY</code> clause then ensures that the results are ordered with those trophies that have been won appearing first, followed by those that have not; within those tiers, the order is randomised (again, if you simply don't care about the order you can remove the <code>, RAND()</code> part which is adding unnecessary overhead).</p>
    singulars
    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.
 

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