我有一张表格,其中包含所有用户的视频下载历史记录:
src_ip vlan_id video_id area date_pl
aaaa A 1 123 xxxx-xx-xx
aaaa A 2 123 xxxx-xx-xx
aaaa B 1 456 xxxx-xx-xx
bbbb A 4 123 xxxx-xx-xx
bbbb C 6 567 xxxx-xx-xx
...
我使用src_ip和vlan_id的组合来识别不同的用户,现在我想随机选择50个不同的用户(这意味着50个不同的src_ip和vlan_id组合)并列出他们的所有下载历史记录。
首先我做了:
SELECT distinct src_ip, vlan_id from video_2 as table2
WHERE date_pl >= '2011-11-29 00:00' AND date_pl <= '2011-12-05 23:55' order by rand() limit 50
然后我做了:
SELECT src_ip, vlan_id, video_id, area from video_2
where video_2.src_ip = table2.src_ip AND video_2.vlan_id = table2.vlan_id
AND date_pl >= '2011-11-29 00:00' AND date_pl <= '2011-12-05 23:55'
但问题是,因为它们是两个独立的查询,所以在第二个查询中,它不知道table2是什么。
如何解决此问题或如何将这两个查询合并为一个?
答案 0 :(得分:2)
CREATE TEMPORARY TABLE table2
AS
SELECT distinct src_ip, vlan_id from video_2
WHERE date_pl >= '2011-11-29 00:00' AND date_pl <= '2011-12-05 23:55'
ORDER BY rand()
LIMIT 50;
SELECT src_ip, vlan_id, video_id, area
FROM
video_2
JOIN
table2 ON video_2.src_ip = table2.src_ip AND video_2.vlan_id = table2.vlan_id';
由于限制在子查询中使用LIMIT, 无法使“table2”在行中派生。否则就是
SELECT
v2.src_ip, v2.vlan_id, v2.video_id, v2.area
FROM
video_2 v2
JOIN
(SELECT distinct v.src_ip, v.vlan_id from video_2 v
WHERE v.date_pl >= '2011-11-29 00:00' AND v.date_pl <= '2011-12-05 23:55'
ORDER BY rand()
LIMIT 50
) table2 ON v2.src_ip = table2.src_ip AND v2.vlan_id = table2.vlan_id;
编辑:限制子查询中的LIMIT主要适用于IN,而不适用于派生表
编辑2:添加了更多别名