计算并打印两个不同表中的列

时间:2016-12-22 01:40:24

标签: mysql

我有两张桌子:'user' and 'user_project'

用户表:

| username | user_type | 
+----------+-----------+
| adam     | CT        |
| bob      | AP        |
| cat      | AP        |

user_project

| projectNo | process | username | 
+-----------+---------+----------+
| 16090001  | ANM     | adam     |
| 16090001  | ANM     | bob      |
| 16090001  | BLD     | adam     |

我想计算同名的外观,显示该用户名,外观数量和user_type

但我只能打印用户名和COUNT。到目前为止我所拥有的:

SELECT username, COUNT(username) names FROM 
    (SELECT username FROM `user_project` WHERE projectNo=16120001
                        UNION ALL
    SELECT username FROM `user` ) t GROUP BY username

这是我的预期输出:

| username | user_type | count | 
+----------+-----------+-------+
| adam     | CT        | 3     |
| bob      | AP        | 2     |
| cat      | AP        | 1     |

如何打印所有三列?

2 个答案:

答案 0 :(得分:1)

一种方法是在user_project表上使用子查询来按用户聚合外观,然后将其连接回user表。

SELECT t1.username,
       t1.user_type,
       COALESCE(t2.num_appearences, 0) AS `count`
FROM user t1
LEFT JOIN
(
    SELECT username, COUNT(*) AS num_appearences
    FROM user_project
    WHERE projectNo = <some_number>
    GROUP BY username
) t2
    ON t1.username = t2.username

答案 1 :(得分:0)

您可以在此处选择DISTINCT列名FROM table_name

SELECT COUNT(DISTINCT username)FROM user_project;