MySQL基于先前的查询结果交织两个查询

时间:2014-06-20 18:53:36

标签: mysql sql

我有一个表:id,client,domain和bytes。我有一个查询,可以通过客户端获得前3位用户:

SELECT client FROM log
GROUP BY 1
ORDER BY SUM(bytes) DESC
LIMIT 3

或按域名

SELECT domain FROM log
GROUP BY 1
ORDER BY SUM(bytes) DESC
LIMIT 3

MySQL是否有办法在没有存储过程的情况下将这两个混合?例如,获取前3个客户端,每个客户端行后跟在单个查询执行中使用的前三个域?

  • 192.168.1.1
    • google.com
    • facebook.com
    • twitter.com
  • 192.168.1.2
    • facebook.com
    • twitter.com
    • ...
  • ...

例如,要从客户端192.168.1.1获取前3个域使用:

SELECT domain FROM log
WHERE client = '192.168.1.1'
GROUP BY 1
ORDER BY SUM(bytes) DESC
LIMIT 3

因此,对于查询#1中的每一行,都应以某种方式执行此查询。到目前为止,我必须显示每个客户端的顶级域名的连锁列表,遗憾的是与同一客户端无关,因为我无法在子查询中访问outer_client

SELECT client AS outer_client, top_domain
FROM log
JOIN (
   SELECT GROUP_CONCAT(t.domain) AS top_domain 
   FROM (
      SELECT domain 
      FROM log
      WHERE client = outer_client 
      GROUP BY 1 
      ORDER BY SUM(bytes)
      LIMIT 5
   ) t
) k
GROUP BY client
ORDER BY SUM(bytes)
LIMIT 5;

4 个答案:

答案 0 :(得分:2)

一个解决方案:

http://sqlfiddle.com/#!2/cc1b1/2/0

SELECT client
  , (SELECT domain
      FROM log
      WHERE client=top_clients.client
      GROUP BY client, domain
      ORDER BY SUM(bytes) DESC
      LIMIT 1) domain1
  , (SELECT domain
      FROM log
      WHERE client=top_clients.client
      GROUP BY client, domain
      ORDER BY SUM(bytes) DESC
      LIMIT 1 OFFSET 1) domain2
  , (SELECT domain
      FROM log
      WHERE client=top_clients.client
      GROUP BY client, domain
      ORDER BY SUM(bytes) DESC
      LIMIT 1 OFFSET 2) domain3
FROM (SELECT client FROM log GROUP BY client ORDER BY SUM(bytes) DESC LIMIT 3) top_clients;

我的输出:

+-------------+--------------+--------------+-------------+
| client      | domain1      | domain2      | domain3     |
+-------------+--------------+--------------+-------------+
| 192.168.1.1 | google.com   | facebook.com | twitter.com |
| 192.168.1.2 | facebook.com | twitter.com  | NULL        |
+-------------+--------------+--------------+-------------+

答案 1 :(得分:0)

假设您可以访问PHPMySQL,并且您的服务器允许它,那么您正在寻找的是VIEW。

您编写SQL以获取数据集。而不是将其保存在临时表中(这将使其静态),您将其保存在VIEW中。拥有该视图后,您可以像使用表一样使用它。实际上,它实际上以表格格式显示数据集,就好像它就是这样 您可以使用JOINS运行查询...您可以使用表格执行任何操作。 这是实际的实时数据。

答案 2 :(得分:0)

这是:

select client,
substring_index(group_concat(domain order by sumbytes desc), ',', 5) as top5domains
from (
  select client, domain, sum(bytes) as sumbytes
  from log
  group by client, domain
) cd
group by client
order by sum(sumbytes) desc
limit 5;

由@Gordon Linoff提供:MySQL GROUP_CONCAT from subquery

答案 3 :(得分:-1)

根据您的问题,您在每个示例中都按相同的顺序排序。如果是这种情况,您返回的行应该已经包含客户端和域。那么这会解决你的问题吗?

SELECT client, domain FROM log
GROUP BY 1
ORDER BY SUM(bytes) DESC
LIMIT 3