Mysql计数行

时间:2014-11-19 08:58:18

标签: mysql sql select count

我有一张桌子msg
 根据我的SQL查询,我需要为各个用户选择COUNT到所有msg acc。 Q1 - >

SELECT COUNT(*) 
FROM msg 
WHERE to = 2 
AND from IN(1,3,4) 
GROUP BY to

Q2->

SELECT COUNT(*) 
FROM msg 
WHERE `from` = 2 
AND `to` IN (1,3,4) 
GROUP BY from

我如何在1个查询中执行此操作? (我的user_id = 2)

msg_id|from|to|msg|
1       2    3 Hi
2       2    3 Hi
3       2    4 Hi
4       3    2 Hi
5       3    4 Hi
6       4    2 Hi
7       3    2 HiBye
8       1    2 Hi
9       2    4 Hi
10      3    2 Hi

预期产出:

user_id|sent_c|got_c|
3        2        3 
4        2        1 
1        0        1

1 个答案:

答案 0 :(得分:1)

可能有几种方法可以给这只特殊的猫皮肤涂抹。这是一个...

  DROP TABLE IF EXISTS my_table;

  CREATE TABLE my_table
  (msg_id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
  ,msg_from INT NOT NULL
  ,msg_to INT NOT NULL
  ,msg VARCHAR(12) NOT NULL
  );

  INSERT INTO my_table VALUES
  (1       ,2    ,3 ,'Hi'),
  (2       ,2    ,3 ,'Hi'),
  (3       ,2    ,4 ,'Hi'),
  (4       ,3    ,2 ,'Hi'),
  (5       ,3    ,4 ,'Hi'),
  (6       ,4    ,2 ,'Hi'),
  (7       ,3    ,2 ,'HiBye'),
  (8       ,1    ,2 ,'Hi'),
  (9       ,2    ,4 ,'Hi'),
  (10      ,3    ,2 ,'Hi');

  SELECT * FROM my_table;
  +--------+----------+--------+-------+
  | msg_id | msg_from | msg_to | msg   |
  +--------+----------+--------+-------+
  |      1 |        2 |      3 | Hi    |
  |      2 |        2 |      3 | Hi    |
  |      3 |        2 |      4 | Hi    |
  |      4 |        3 |      2 | Hi    |
  |      5 |        3 |      4 | Hi    |
  |      6 |        4 |      2 | Hi    |
  |      7 |        3 |      2 | HiBye |
  |      8 |        1 |      2 | Hi    |
  |      9 |        2 |      4 | Hi    |
  |     10 |        3 |      2 | Hi    |
  +--------+----------+--------+-------+
  10 rows in set (0.00 sec)

  SELECT user_id
       , SUM(status = 'sent') s
       , SUM(status = 'received') r
    FROM
       (  SELECT  msg_id,msg_to user_id,'sent' status FROM my_table WHERE msg_from = 2
          UNION
          SELECT  msg_id,msg_from,'received' FROM my_table WHERE msg_to = 2
       ) x
   WHERE user_id IN(1,3,4)
   GROUP
      BY user_id;

 +---------+------+------+
 | user_id | s    | r    |
 +---------+------+------+
 |       1 |    0 |    1 |
 |       3 |    2 |    3 |
 |       4 |    2 |    1 |
 +---------+------+------+