MYSQL:每个用户的组计数特定列?

时间:2019-12-07 15:17:29

标签: mysql sql group-by aggregate-functions

我想使用3个表中的数据为每个特定用户计数列。

表1(用户):

CREATE TABLE `datastore`.`users` ( `uid` INT NOT NULL AUTO_INCREMENT ,  `name` VARCHAR(30) NOT NULL DEFAULT 'john' ,  `class` VARCHAR(20) NOT NULL DEFAULT 'NEW' ,    PRIMARY KEY  (`uid`)) ENGINE = InnoDB;
INSERT INTO `users` (`uid`, `name`, `class`) VALUES (NULL, 'john', 'NEW'), (NULL, 'mark', 'OLD');

示例:

uid name    class
1   john    NEW
2   mark    OLD

表2(数据):

CREATE TABLE `datastore`.`data` ( `id` INT NOT NULL AUTO_INCREMENT ,  `source` VARCHAR(30) NULL DEFAULT NULL ,  `destination` VARCHAR(30) NULL DEFAULT NULL ,    PRIMARY KEY  (`id`)) ENGINE = InnoDB;
INSERT INTO `data` (`id`, `source`, `destination`) VALUES (NULL, 'NETWORK', 'SERVER_1'), (NULL, 'STATION', 'SERVER_2'), (NULL, 'DATASTORE', 'SERVER_1');

示例:

id  source  destination
1   NETWORK     SERVER_1
2   STATION     SERVER_2
3   DATASTORE   SERVER_1

表3(访问权限):

CREATE TABLE `datastore`.`access` ( `id` INT(11) NOT NULL AUTO_INCREMENT ,  `uid` INT(11) NULL DEFAULT NULL ,  `source` VARCHAR(30) NULL DEFAULT NULL ,    PRIMARY KEY  (`id`)) ENGINE = InnoDB;
INSERT INTO `access` (`id`, `uid`, `source`) VALUES (NULL, '1', 'NETWORK'), (NULL, '2', 'STATION'), (NULL, '1', 'STATION'), (NULL, '1', 'STATION');

示例:

id  uid source
1   1   NETWORK
2   2   STATION
3   1   STATION
4   1   STATION

到目前为止我尝试过的事情:

SELECT access.uid, data.destination, COUNT(*) as count FROM data, access WHERE access.source = data.source GROUP BY destination, uid

结果:

uid destination count   
1   SERVER_1    1
1   SERVER_2    2
2   SERVER_2    1

我还想用用户名链接什么

所需结果:

uid name destination    count   
1   john SERVER_1       1
1   john SERVER_2       2
2   mark SERVER_2       1

3 个答案:

答案 0 :(得分:3)

您似乎还需要为用户加入

 SELECT access.uid
  , users.name
  , data.destination
  , COUNT(*) as count 
FROM data
INNER JOIN  access ON  access.source = data.source 
INNER JOIN users ON users.uid = access.uid
GROUP BY destination, uid, users.name

并且建议您不要使用基于where ..的(旧)隐式连接语法,而应使用显式连接语法。

答案 1 :(得分:2)

使用聚合:

select
    a.uid,
    u.name,
    d.destination,
    count(*)
from 
    access a 
    inner join users u on u.uid = a.uid
    inner join data on d.source = a.source
group by
    a.uid,
    u.name,
    d.destination

答案 2 :(得分:2)

获取用户名所需要做的就是将查询加入表users

SELECT u.uid, u.name, t.destination, t.count
FROM users u INNER JOIN (
  SELECT a.uid, d.destination, COUNT(*) AS count 
  FROM data d 
  INNER JOIN access a ON a.source = d.source 
  GROUP BY d.destination, a.uid
) t ON u.uid = t.uid  
ORDER BY u.uid, t.destination

请参见demo
结果:

| uid | name | destination | count |
| --- | ---- | ----------- | ----- |
| 1   | john | SERVER_1    | 1     |
| 1   | john | SERVER_2    | 2     |
| 2   | mark | SERVER_2    | 1     |