带连接的双重计数查询

时间:2013-12-03 15:25:34

标签: mysql

我有四个表,我需要获得2个计数,然后按用户表对它们进行分组。

SELECT  (
    SELECT COUNT(*)
        FROM  user_share us
        INNER JOIN user_share_recipient usr
        ON usr.share_id = us.id
        WHERE usr.sent_at BETWEEN '2013-11-01' AND '2013-11-31'
    ) AS Shares,
    (
    SELECT COUNT(*)
    FROM   resource_tracking
    WHERE created_at BETWEEN '2013-11-01' AND '2013-11-31'
    ) AS Views

FROM    dual

这可以从三个表中获取总计数,但我需要加入第四个用户表,然后按用户名对每个表进行分组。所以我可以

select first name, last name (then the shares count)(then the views count) 
from users (join the tables above on user_id columns on both tables)
 group by username

所以我最终得到的结果如下:

First Name    Last Name     Shares    Views

  John         Smith         20        40     

这甚至可能吗?我不能使用临时表

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT u.first_name, 
       u.last_name, 
       COALESCE(Shares.s_count,0), 
       COALESCE(VIEWS.v_count,0)
FROM users u
LEFT JOIN (
  SELECT us.user_id, COUNT(*) AS s_count
  FROM user_share us
  INNER JOIN user_share_recipient usr ON usr.share_id = us.id
  WHERE usr.sent_at BETWEEN '2013-11-01' AND '2013-11-31'
  GROUP BY us.user_id
  ) AS Shares ON u.user_id = Shares.user_id
LEFT JOIN (
  SELECT user_id, COUNT(*) AS v_count
  FROM resource_tracking
  WHERE created_at BETWEEN '2013-11-01' AND '2013-11-31'
  GROUP BY user_id
  ) AS VIEWS ON u.user_id = VIEWS.user_id

即使没有共享或视图,也使用LEFT JOIN获取结果。在这些情况下,使用COALESCE将它们设为0。

答案 1 :(得分:0)

在您的第一个查询中,使用“来自用户”而不是“来自双重”。然后,在内部子选择上,添加仅选择特定用户的计数的子句。像这样:

SELECT  username, max(FIRST_NAME), max(LAST_NAME),
   (
    SELECT COUNT(*)
        FROM  user_share us
        INNER JOIN user_share_recipient usr
        ON usr.share_id = us.id
        WHERE usr.sent_at BETWEEN '2013-11-01' AND '2013-11-31'
          and users.USER_ID = us.user_id
    ) AS Shares,
    (
    SELECT COUNT(*)
    FROM   resource_tracking
    WHERE created_at BETWEEN '2013-11-01' AND '2013-11-31'
     and users.USER_ID = resource_tracking.user_id
    ) AS Views

FROM  users
group by username

答案 2 :(得分:0)

SELECT um.firstname, um.lastname, 
(
  SELECT COUNT(*)
  FROM user_share AS us
    INNER JOIN user_share_recipient AS usr
    ON usr.share_id = us.id
  WHERE usr.sent_at BETWEEN '2013-11-01' AND '2013-11-31'
    AND um.user_id = us.user_id
) AS Shares,
(
  SELECT COUNT(*)
  FROM resource_tracking AS rt
  WHERE rt.created_at BETWEEN '2013-11-01' AND '2013-11-31'
    AND um.user_id = rt.user_id
) AS Views,
FROM users AS um