How to make a dynamic limit in MySQL?
<p>I have a table like this:</p>

<pre><code>// notifications
+----+--------------+------+---------+------------+
| id |      event   | seen | id_user | time_stamp |
+----+--------------+------+---------+------------+
| 1  | vote         | 1    | 123     | 1464174617 |
| 2  | comment      | 1    | 456     | 1464174664 |
| 3  | vote         | 1    | 123     | 1464174725 |
| 4  | answer       | 1    | 123     | 1464174813 |
| 5  | comment      | NULL | 456     | 1464174928 |
| 6  | comment      | 1    | 123     | 1464175114 |
| 7  | vote         | NULL | 456     | 1464175317 |
| 8  | answer       | NULL | 123     | 1464175279 |
| 9  | vote         | NULL | 123     | 1464176618 |
+----+--------------+------+---------+------------+ 
</code></pre>

<p>I'm trying to select at least 15 rows for specific user. Just there is two conditions:</p>

<ol>
<li><p>Always all unread rows (<code>seen = NULL</code>) should be matched, even if they are more than 15 rows.</p></li>
<li><p>If the number of unread rows is more than 15, then it also should select 2 read rows (<code>seen = 1</code>).</p></li>
</ol>

<hr>

<p><strong>Examples:</strong> <code>read</code> is the number of read rows and <code>unread</code> is the number of unread rows in <code>notifications</code> table.</p>

<pre><code> read | unread |          output should be           
------|--------|-------------------------------------
 3    | 8      | 11 rows                             
 12   | 5      | 15 rows (5 unread, 10 read)         
 20   | 30     | 32 rows (30 unread, 2 read)         
 10   | 0      | 10 rows (0 unread, 10 read)         
 10   | 1      | 11 rows (1 unread, 10 read)         
 10   | 6      | 15 rows (6 unread, 9 read)          
 100  | 3      | 15 rows (3 unread, 12 read)         
 3    | 100    | 102 rows (100 unread, 2 read)       
</code></pre>

<hr>

<p>Here is my current query, it doesn't support second condition.</p>

<pre><code>SELECT id, event, seen, time_stamp 
 FROM notifications n
 WHERE id_user = :id AND seen IS NULL
) UNION 
(SELECT id, event, seen, time_stamp 
 FROM notifications n
 WHERE id_user = :id 
 ORDER BY (seen IS NULL) desc, time_stamp desc
 LIMIT 15
)
ORDER BY (seen IS NULL) desc, time_stamp desc;
</code></pre>