在Mysql中加入两个查询

时间:2012-01-13 10:33:19

标签: mysql

我的数据库表有四列:

src_ip   video_id  vlan_id  area      

query1= "SELECT area, count(*), count(DISTINCT video_id) FROM video_2 WHERE date_pl >= '2011-11-29 00:00' AND date_pl <= '2011-12-05 23:55' GROUP BY area"
query2= "SELECT area, count(*) as distinctCount FROM (SELECT DISTINCT src_ip, vlan_id, area FROM video_2 WHERE date_pl >= '2011-11-29 00:00' AND date_pl <= '2011-12-05 23:55') distinctVideos GROUP BY area"

执行query1后,结果为:

AREA   # of Total requests    # of Distinct video
area1  1234                   433
area2  3456                   234
...

执行query2后,结果为:

AREA   # of users
area1  23
area2  34
area3  56
...

但是如何将这两个查询合并为一个,那么我可以在一个数据集中得到结果:

AREA   total requests   # of distinct video   # of users   
area1  1234             433                   23
...

之后如何根据&#34;总请求&#34;对结果进行降序或提升排序。或&#34;用户数&#34;,在哪里添加&#34; ORDER BY&#34;在查询?

非常感谢!

1 个答案:

答案 0 :(得分:0)

我不确定我是否遗漏了任何东西,但也许你需要的是这样的东西?

SELECT * FROM (SELECT area, count(*) as total_requests, count(DISTINCT video_id) as total_videos, count(DISTINCT src_ip) as total_users 
FROM video_2 
WHERE date_pl >= '2011-11-29 00:00' AND date_pl <= '2011-12-05 23:55'
GROUP BY area) as a ORDER BY total_requests

如果没有外部选择,您也可以这样做 - 只需按顺序插入计数(某物)即可。