Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>It's pretty easy if you don't do the sorting by most countries in common (you could do it in code later if the result sets won't be too large):</p> <pre class="lang-sql prettyprint-override"><code>SELECT o.id userid, u_cs.countryid FROM users u JOIN countryselection u_cs ON (u.id = u_cs.userid) JOIN countryselection o_cs ON (u_cs.countryid = o_cs.countryid) JOIN users o ON (o_cs.userid = o.id) WHERE u.id = :userid AND -- The user we want u.id &lt;&gt; o.id AND -- Exclude ourselves ( -- Check whether the other person is -- compatible with us (u.pref_m = 1 AND o.gender = 'male') OR (u.pref_f = 1 AND o.gender = 'female') ) AND ( -- Check whether we're compatible with the -- other person (o.pref_m = 1 AND u.gender = 'male') OR (o.pref_f = 1 AND u.gender = 'female') ) </code></pre> <p><a href="http://sqlfiddle.com/#!2/5ee7c/23" rel="nofollow">SQL Fiddle</a></p> <hr> <p>If you <em>do</em> want the sorting, I think the best option is to use <code>GROUP_CONCAT</code> (because MySQL sucks and doesn't support windowing/analytic functions).</p> <pre class="lang-sql prettyprint-override"><code>SELECT o.id userid, GROUP_CONCAT(u_cs.countryid) countries FROM users u JOIN countryselection u_cs ON (u.id = u_cs.userid) JOIN countryselection o_cs ON (u_cs.countryid = o_cs.countryid) JOIN users o ON (o_cs.userid = o.id) WHERE u.id = :userid AND -- The user we want u.id &lt;&gt; o.id AND -- Exclude ourselves ( -- Check whether the other person is -- compatible with us (u.pref_m = 1 AND o.gender = 'male') OR (u.pref_f = 1 AND o.gender = 'female') ) AND ( -- Check whether we're compatible with the -- other person (o.pref_m = 1 AND u.gender = 'male') OR (o.pref_f = 1 AND u.gender = 'female') ) GROUP BY o.id ORDER BY COUNT(u_cs.countryid) DESC </code></pre> <p>You could probably pull this off with some nasty subqueries too, but I get the feeling it'll kill performance.</p> <p><a href="http://sqlfiddle.com/#!2/5ee7c/22" rel="nofollow">SQL Fiddle</a></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. 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