我有一张桌子:
查询:
SELECT DISTINCT LEAST(Message.MesFrom, Message.MesTo) AS user1
, GREATEST(Message.MesFrom, Message.MesTo) AS user2
FROM Message
WHERE MesFrom =1 OR MesTo = 1
ORDER BY ID DESC
输出是具有userID 1
消息的用户ID下一步是:
while($row = mysqli_fetch_array($result)){if ($row['user1'] == $uid){$userid = $row['user2'];} else { $userid = $row['user1']; }echo $userid;
所以我得到的页面: ID 2 4
我现在要做的是计算New = 1条消息的数量,以便输出
ID NEW
2 3
4 1
对不起,不知道怎么把表放在这里(
答案 0 :(得分:1)
SELECT mesto, sum(new)
FROM Message
group by mesto
答案 1 :(得分:1)
这应该返回你想要的结果
SELECT MesTo, SUM(new) AS NewMessages
FROM Message
GROUP BY MesTo
答案 2 :(得分:0)
如果您只是想让user1
始终拥有较小的ID而user2
始终拥有较大的ID,并计算它们之间的新消息数量,那么这应该是给你你想要的东西。
SELECT user1,user2,sum(new) as newMessages
FROM
(SELECT
LEAST(mesfrom,mesto) as user1,
GREATEST(mesfrom,mesto) as user2,
new
FROM message)as T1
GROUP BY user1,user2
这可以简化为
SELECT
LEAST(mesfrom,mesto) as user1,
GREATEST(mesfrom,mesto) as user2,
sum(new) as newMessages
FROM
message
GROUP BY user1,user2