title: MySQL query to get "intersection" of numerous queries with limits
body: <p>Assume I have a single mySQL table (users) with the following fields:</p>
  
  <pre><code>userid  
  gender  
  region  
  age  
  ethnicity  
  income
  </code></pre>
  
  <p>I want to be able to return the number of total records based on the number a user enters.  Furthermore, they will also be providing additional criteria.</p>
  
  <p>In the simplest example, they may ask for 1,000 records, where 600 records should have gender = 'Male' and 400 records where gender = 'Female'.  That's simple enough to do.</p>
  
  <p>Now, go one step further.  Assume they now want to specify Region:</p>
  
  <pre><code>GENDER  
      Male:   600 records  
      Female: 400 records  
  
  REGION  
      North:  100 records  
      South:  200 records  
      East:   300 records  
      West:   400 records
  </code></pre>
  
  <p>Again, only 1000 records should be returned, but in the end, there must be 600 males, 400 females, 100 Northerners, 200 Southerners, 300 Easterners and 400 Westerners.</p>
  
  <p>I know this isn't valid syntax, but using pseudo-mySQL code, it hopefully illustrates what I'm trying to do:</p>
  
  <pre><code>(SELECT * FROM users WHERE gender = 'Male' LIMIT 600  
  UNION  
  SELECT * FROM users WHERE gender = 'Female' LIMIT 400)
  
  INTERSECT
  
  (SELECT * FROM users WHERE region = 'North' LIMIT 100  
  UNION  
  SELECT * FROM users WHERE region = 'South' LIMIT 200  
  UNION  
  SELECT * FROM users WHERE region = 'East' LIMIT 300  
  UNION  
  SELECT * FROM users WHERE region = 'West' LIMIT 400)
  </code></pre>
  
  <p>Note that I'm not looking for a one-time query.  The total number of records and the number of records within each criteria will constantly be changing based on input by the user.  So, I'm trying to come up with a generic solution that can be re-used over and over, not a hard-coded solution.</p>
  
  <p>To make things more complicated, now add more criteria. There could also be age, ethnicity and income each with their own set number of records for each group, additional code appended to above:</p>
  
  <pre><code>INTERSECT
  
  (SELECT * FROM users WHERE age &gt;= 18 and age &lt;= 24 LIMIT 300  
  UNION  
  SELECT * FROM users WHERE age &gt;= 25 and age &lt;= 36 LIMIT 200  
  UNION  
  SELECT * FROM users WHERE age &gt;= 37 and age &lt;= 54 LIMIT 200  
  UNION  
  SELECT * FROM users WHERE age &gt;= 55 LIMIT 300)  
  
  INTERSECT
  
  etc.
  </code></pre>
  
  <p>I'm not sure if this is possible to write in one query or if this requires multiple statements and iterations.</p>