我面临的场景是,我有一个通知/消息表。我想做的是获取:
- 最多10条消息
- 所有未读邮件
有一个限制,即如果有超过10条未读消息,我们只能获取这些消息。所以基本上,我希望最后有10条未读消息(包括未读和已读消息),或者如果有10条以上的消息,最后有n条未读。
知道吗?我无法向你提供我一直在尝试的任何例子,因为我甚至还没有到那个地步。我提出的唯一解决方案是基于UNION或SELECT FROM,不幸的是,这两种方案都没有得到条令的支持。
@编辑
为了明确起见,我想获取所有未读消息,并且只有在未读消息少于10条的情况下才能获取已读消息,以显示至少10条消息。
作为临时解决方案,我决定使用两个查询。一个是检查未读消息的计数,在此基础上,我要么获取10条消息(如果计数小于10),要么获取所有未读消息,如果计数大于10。但如果可能的话,我宁愿使用单个查询,这就是我想要的
您可以通过使用订单。您只需要在if中更改比较。我不知道如何比较你的信息的状态
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>