+-------------------+---------------------+------+-----+---------+----------------+
| RowId | MSGID| Received| UID | Default | |
+-------------------+---------------------+------+-----+---------+----------------+
| 1 | 1 | NO | 1 | NULL | |
| 2 | 1 | YES | 3 | NULL | |
| 3 | 1 | YES | 4 | NULL | |
| 4 | 1 | YES | 5 | NULL | |
| 5 | 5 | YES | 2 | NULL | |
| 6 | 2 | YES | 8 | NULL | |
| 7 | 1 | YES | 9 | NULL | |
+-------------------+---------------------+------+-----+---------+----------------+
这是我在MySQL中的表格。
如何获取MSGID = 1
的消息数量和已收到消息的用户数为MSGID = 1
的消息数以及未收到消息的用户数为MSGID = 1
的消息数量?
我想在一个循环中这样做,以便我可以得到三个值,如[5,4,1]。因此每次页面加载查询时都会检查数据库并更新集合。请帮忙
答案 0 :(得分:2)
首先计算MSGID = 1
的消息数SELECT COUNT(RowID) FROM tableName WHERE MSGID = 1
获取已收到msg的用户数量,其中MSGID = 1
SELECT COUNT(DISTINCT UID) FROM tableName WHERE MSGID = 1
获取未收到MSGID = 1的消息的用户数量
SELECT COUNT(DISTINCT UID) FROM tableName WHERE MSGID =1 AND Received = 'NO'
答案 1 :(得分:0)
您可以在一个查询中执行此操作。我没有看到循环的好处?
select count(*)
, count(distinct uid)
, count(distinct case when received = 'NO' then uid else null end case)
from table_name
where msgid = 1
这应该是多个表,
1)用户,在uid上是截然不同的
2)消息,在msgid上是不同的,收到的是/否。
答案 2 :(得分:0)
要使用一个查询来获取它,您可以执行以下所有的联合:
SELECT COUNT(RowID) AS 'Col1', '' AS 'Col2', '' AS 'Col3'
FROM tableName WHERE MSGID = 1
UNION ALL
SELECT '' AS 'Col1', COUNT(DISTINCT UID) AS 'Col2', '' AS 'Col3'
FROM tableName WHERE MSGID = 1
UNION ALL
SELECT '' AS 'Col1', '' AS 'Col2' , COUNT(DISTINCT UID) AS 'Col3'
FROM tableName WHERE MSGID =1 AND Received = 'NO'
希望这对你有用。