您可以使用order by。您只需更改中的比較如果。我不知道如何來比較你的消息的狀態
SELECT *
FROM (
SELECT
y.*
, @nr := @nr +1 as nr
FROM your_table y
CROSS JOIN (SELECT @nr:=0) as init
ORDER BY if(`status` = 'unread', 1,2)
) as result
WHERE
`status` = 'read'
OR
(`status` = 'unread' and nr <= 10);
樣品
mysql> SELECT * FROM your_table;
+----+--------+
| id | status |
+----+--------+
| 1 | unread |
| 2 | unread |
| 3 | unread |
| 4 | unread |
| 5 | unread |
| 6 | unread |
| 7 | read |
| 8 | unread |
| 9 | read |
| 10 | read |
| 11 | read |
| 12 | read |
| 13 | unread |
| 14 | unread |
| 15 | unread |
| 16 | unread |
| 17 | unread |
| 18 | read |
| 19 | read |
+----+--------+
19 rows in set (0,00 sec)
mysql>
mysql> SELECT y.status , count(*)
-> FROM your_table y
-> GROUP BY y.status;
+--------+----------+
| status | count(*) |
+--------+----------+
| read | 7 |
| unread | 12 |
+--------+----------+
2 rows in set (0,00 sec)
mysql>
結果
mysql> SELECT *
-> FROM (
-> SELECT
-> y.*
-> , @nr := @nr +1 as nr
-> FROM your_table y
-> CROSS JOIN (SELECT @nr:=0) as init
-> ORDER BY if(`status` = 'unread', 1,2)
->) as result
-> WHERE
-> `status` = 'read'
-> OR
-> (`status` = 'unread' and nr <= 10);
+----+--------+------+
| id | status | nr |
+----+--------+------+
| 1 | unread | 1 |
| 2 | unread | 2 |
| 3 | unread | 3 |
| 4 | unread | 4 |
| 5 | unread | 5 |
| 6 | unread | 6 |
| 8 | unread | 7 |
| 13 | unread | 8 |
| 14 | unread | 9 |
| 15 | unread | 10 |
| 7 | read | 13 |
| 9 | read | 14 |
| 10 | read | 15 |
| 11 | read | 16 |
| 12 | read | 17 |
| 18 | read | 18 |
| 19 | read | 19 |
+----+--------+------+
17 rows in set (0,00 sec)
mysql>
是的,但是這將在任何情況下限制爲10如果超過10個,我需要取回所有未讀郵件。 – user1970395
@ user1970395 - 對不起 - 我已更改我的回答 –
非常感謝,你還是有一個小小的錯誤 - 在'where'條件中的'status'應該是相反的方法;)這很有幫助,是的。不幸的是,這種查詢在'Doctrine2'中不會很好地發揮,因爲我不能在'from'子句中放置子查詢。我會繼續嘗試! – user1970395