有连接和计数的mysql查询

时间:2014-09-04 21:34:27

标签: mysql database

我需要帮助从连接在一起的mysql数据库中的两个不同表中的列中获取前5个结果及其计数。

table1 cols
-------
id, country, timestamp

table2 cols
--------
id, table1_id, reason

得到的结果ID是前5个国家及其在两个时间戳之间找到的次数,以及用于生成第一个计数的所有行的前5个原因及其计数。 table1和table2之间存在一对多的关系。这让我很难过,我很感激你能给我的任何见解。

2 个答案:

答案 0 :(得分:0)

您想要返回的结果集并不完全清楚。

这对您有所帮助:

SELECT t.country
     , COUNT(DISTINCT t.id) AS count_table1_rows
     , COUNT(r.id)          AS count_table2_rows
     , COUNT(*)             AS count_total_rows
  FROM table1 t
  LEFT
  JOIN table2 r
    ON r.table1_id = t.id
 WHERE t.timestamp >= NOW() - INTERVAL 7 DAY
   AND t.timestamp  < NOW()
 GROUP BY t.country
 ORDER BY COUNT(DISTINCT t.id) DESC
 LIMIT 5

这将返回最多5行,每个国家/地区一行,table1中的行数,table2中找到的行数,以及返回的总行数。

LEFT关键字指定“外部”连接操作,即使在table2中找不到匹配的行,也会返回table1中的行。

要获得与每个国家/地区相关联的每个“原因”的计数,您可以执行以下操作:

SELECT t.country
     , COUNT(DISTINCT t.id) AS count_table1_rows
  FROM table1 t
  LEFT
  JOIN ( SELECT s.country
              , r.reason
              , COUNT(*) AS cnt_r
           FROM table1 s 
           JOIN table2 r
             ON s.table1_id = t.id
          WHERE s.timestamp >= NOW() - INTERVAL 7 DAY
            AND s.timestamp  < NOW()
          GROUP
             BY s.country
              , r.reason
       ) u
    ON u.country = t.country 
 WHERE t.timestamp >= NOW() - INTERVAL 7 DAY
   AND t.timestamp  < NOW()
 GROUP
    BY t.country
     , u.reason
 ORDER
    BY COUNT(DISTINCT t.id) DESC
     , t.country DESC
     , u.cnt_r DESC
     , u.reason DESC

此查询不会“限制”返回的行。可以修改查询以仅返回返回的行的子集,但这可能会变得复杂。在我们解决添加“前5个前5个”类型限制的复杂性之前,我们希望确保查询返回的行是我们实际需要的行的超集。

答案 1 :(得分:0)

这是你想要的吗?

select t2.reason, count(*)
from (select t1.country, count(*)
      from table1 t1
      where timestamp between @STARTTIME and @ENDTIME
      group by country
      order by count(*) desc
      limit 5
     ) c5 join
     table1 t1
     on c5.country = t1.country and
        t1.timestamp between @STARTTIME and @ENDTIME join
     table2 t2
     on t2.table1_id = t1.id
group by t2.reason;

c5子查询获得五个国家/地区。另外两个带回最终聚合的数据。

相关问题