SQL组由2个字段组成

时间:2016-09-02 07:05:18

标签: mysql sql group-by

我拿到了那张桌子:

table_1:
obj_id row_1

table_2:
obj_id row_2

table_3:
obj_id row_3

我通过以下方式计算每位用户的匹配数:

id, user_a, user_b, score
1,       3,      7,   19
2,       8,      3,   20
3,       3,      2,   10
4,       7,      6,   2
5,       3,      6,   7

我现在想要使用usertable添加用户电子邮件:

select user, count(*)
from
(
    select user_a as user from tablename
    union all
    select user_b from tablename
) dt
group by user

我试过这个:

COUNT(*), user,  email
4,       3,      user3@mail.com
2,       7,      user7@mail.com
1,       8,      user8@mail.com
1,       2,      user2@mail.com
2,       6,      user6@mail.com

但是语法错误:

SELECT user, count(*) 
FROM ( 
SELECT user_a AS user, ut.email
   FROM tablename
   UNION ALL 
      SELECT user_b
      FROM tablename
) dt 
WHERE user IS NOT NULL
LEFT JOIN usertable ut ON ut.id = user
GROUP BY user

有什么想法吗?

1 个答案:

答案 0 :(得分:4)

在派生表中执行UNION ALL,以获取一列用户。 GROUP BY它的结果。

select user, count(*)
from
(
    select user_a as user from tablename
    union all
    select user_b from tablename
) dt
group by user

回答更新的问题:

SELECT dt.user, ut.email, count(*) 
FROM
( 
    SELECT user_a AS user FROM tablename
    UNION ALL 
    SELECT user_b FROM tablename
) dt 
LEFT JOIN usertable ut ON ut.id = dt.user
GROUP BY dt.user, ut.email