簡體   English   中英

MySQL-如何在兩個字段上分組並計數

[英]MySQL - How to group by on two fields and count

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

或者,如果您的代碼更少

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM