在行ID不匹配的两个表上计数(*)行。

时间:2014-06-17 19:01:25

标签: mysql join

对此感到头疼:

我需要计算(*)现在和1天之前两个表中的行数,其中表1中的historyId!=表2中的historyId和userId =?。然后我需要返回两个表的所有行的总和。

如果表1中的historyId与表2中的historyId相等,则只需将其计为一行,而不是两行。

查询一个

    SELECT HOUR(date) as hr, historyId, COUNT(*) as num_rows 
    FROM webHistory WHERE userId=? AND date BETWEEN (SYSDATE() - INTERVAL 1 DAY) 
    AND SYSDATE() GROUP BY HOUR(date);

查询两个

    SELECT HOUR(date) as hr, historyId, COUNT(*) as num_rows 
    FROM locationHistory WHERE userId=? AND date BETWEEN (SYSDATE() - INTERVAL 1 DAY) 
    AND SYSDATE() GROUP BY HOUR(date);

我一直在看JOIN,但我完全陷入困境,不知道甚至要搜索下一个,更不用说冒险和测试的路线了。

2 个答案:

答案 0 :(得分:1)

你可以在这里使用A UNION:

  SELECT HOUR(date) as hr, historyId, COUNT(*) as num_rows 
    FROM webHistory WHERE userId=? AND date BETWEEN (SYSDATE() - INTERVAL 1 DAY) 
    AND SYSDATE() GROUP BY HOUR(date)
 UNION
  SELECT HOUR(date) as hr, historyId, COUNT(*) as num_rows 
   FROM locationHistory WHERE userId=? AND date BETWEEN (SYSDATE() - INTERVAL 1 DAY) 
   AND SYSDATE() GROUP BY HOUR(date);

答案 1 :(得分:1)

我认为你想使用union

select count(distinct historyid)
from (select hour(date) as hr, historyid
      from webhistory
      where userid = ? and date between sysdate() - interval 1 day and sysdate()
      union all
      select hour(date) as hr, historyid
      from locationhistory
      where userid = ? and date between sysdate() - interval 1 day and sysdate()
     ) t
group by hr;
相关问题