在连接的表上显示多个计数值

时间:2014-08-12 20:36:11

标签: sql

我正在尝试计算2个表中存在的userID, 我还在userID上有一个内部联接,以便我可以根据另一个表中的BadgeID搜索一个表的计数。 到目前为止,它返回一个表的用户数,但我似乎无法弄清楚如何在两个表上返回userID的计数,任何建议?

   SELECT DISTINCT live_event.usid, COUNT(1) AS membercount 
   FROM live_event
   INNER JOIN member_badges ON live_event.usid = member_badges.usid
   WHERE bdgid = 14

3 个答案:

答案 0 :(得分:0)

不确定你在找什么;但根据我能理解的,子查询可能是您想要去的路线吗?

    select
        (select count(*) from firsttable where userid = {userid})
    as count1,
        (select count(*) from secondtable where userid = {userid})
    as count2

{userid}将是你的bdgid。

答案 1 :(得分:0)

尝试使用union select来连接两个表的结果

select useid, count(*) from (
select useid from firsttable
union select useid from second table ) group by useid

答案 2 :(得分:0)

试试这个:

SELECT
  user_id,
  COALESCE(MAX(
    CASE
      when tbl_name='live_event' then cnt_records
      else null
    END), 0) as cnt_live_event,
  COALESCE(MAX(CASE
        when tbl_name='member_badges' then cnt_records
        else null
      END), 0) as cnt_member_badges
FROM
(
  SELECT
    'live_event' AS tbl_name,
    usid as user_id,
    count(*) AS cnt_records
  FROM live_event
  GROUP BY 'live_event', usid
  UNION
  SELECT
    'member_badges',
    usid as user_id,
    count(*)
  FROM member_badges
  GROUP BY 'member_badges', usid
) grouped_counts
GROUP BY user_id
ORDER BY user_id;

即使usid仅存在于其中一个表中,上述查询也会为您提供用户计数。