MySQL - 如何在两个字段上进行分组并计数

时间:2014-10-23 11:58:51

标签: mysql sql

CREATE TABLE IF NOT EXISTS `usuarios` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user1` varchar(255) DEFAULT NULL,
  `user2` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;

INSERT INTO `usuarios` (`id`, `user1`, `user2`) VALUES
(1, 'pepe', NULL),
(2, 'pepe', 'juan'),
(3, 'juan', NULL),
(4, 'juan', NULL),
(5, 'juan', 'pepe'),
(6, NULL, 'pepe'),
(7, 'pepe', 'juan');

我需要提出一个问题:我已经这样做了:

SELECT
`user1`,
COUNT(`id`) AS Total
FROM usuarios
WHERE (`user1` is not null)
GROUP BY `user1`
UNION
SELECT
`user2`,
COUNT(`id`) AS Total
FROM usuarios
WHERE (`user2` is not null)
GROUP BY `user2`

但结果是:

user1    total
juan      3
pepe      3
juan      2
pepe      2

我需要删除重复的名称,加总数,这就是结果:

user1    total
juan      5
pepe      5

1 个答案:

答案 0 :(得分:1)

或者,如果你的代码更少......

SELECT user,COUNT(*) FROM
     (
       SELECT user1 user FROM usuarios
       UNION ALL
       SELECT user2 FROM usuarios
     ) x
 WHERE user IS NOT NULL
 GROUP 
    BY user;