mySQL DISTINCT和SUM

时间:2013-11-24 20:59:27

标签: mysql

我有一张桌子:

enter image description here

查询:

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

对不起,不知道怎么把表放在这里(

SQLFiddle Example

3 个答案:

答案 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

sqlFiddle code

这可以简化为

SELECT
    LEAST(mesfrom,mesto) as user1,
    GREATEST(mesfrom,mesto) as user2,
    sum(new) as newMessages
FROM
    message
GROUP BY user1,user2

sqlFiddle code simplified