这很复杂,所以希望我能说清楚。
我有两张桌子:
views:
+---------------------+-------------+------------------+
| time | remote_host | referer |
+---------------------+-------------+------------------+
| 0000-00-00 00:00:00 | 10.0.13.2 | http://foo.com/a |
| 0000-00-00 00:00:00 | 10.0.13.1 | http://foo.com/b |
| 0000-00-00 00:00:00 | 10.0.13.2 | http://moo.com |
| 0000-00-00 00:00:00 | 10.0.13.2 | http://hi.com |
| 0000-00-00 00:00:00 | 10.0.13.1 | http://foo.com/c |
+---------------------+-------------+------------------+
test_websites:
+----+----------------+------+
| id | url | name |
+----+----------------+------+
| 1 | http://foo.com | |
| 2 | http://moo.com | |
+----+----------------+------+
我的查询非常符合我的要求:
SELECT COUNT(*) as count, remote_host, url FROM test_websites
JOIN views ON referer LIKE CONCAT(url, '%')
GROUP BY test_websites.url
ORDER BY count DESC LIMIT 10;
结果如下:
+-------+-------------+----------------+
| count | remote_host | url |
+-------+-------------+----------------+
| 3 | 10.0.13.2 | http://foo.com |
| 1 | 10.0.13.2 | http://moo.com |
+-------+-------------+----------------+
要解释一下,我试图获得前10个被浏览的网站,但网站网址是在test_websites中定义的。由于http://foo.com
是test_websites中的条目,因此以http://foo.com
开头的所有条目都应计为"一个网站。"因此,加入基于LIKE
条件,并且在结果中正确计算3 http://foo.com。
所以,问题是我希望remote_host成为那些以http://foo.com开头的视图中出现最多的条目。在这种情况下,在视图表中以http://foo.com开头有两行,其中10.0.13.1作为remote_host,因此结果应该显示10.0.13.1是remote_host列,而不是显示出来的remote_host第一个以http://foo.com开头的条目,就像现在一样。
感谢。
答案 0 :(得分:1)
<强>已更新强>
请尝试以下更正的查询:
SELECT
COUNT(*) as count,
(
SELECT A.remote_host
FROM views AS A
WHERE A.referer LIKE CONCAT(test_websites.url, '%')
GROUP BY A.remote_host
ORDER BY COUNT(1) DESC
LIMIT 1
) AS max_count_remote_host,
test_websites.url
FROM
test_websites
JOIN views ON views.referer LIKE CONCAT(test_websites.url, '%')
GROUP BY
test_websites.url
ORDER BY
count DESC LIMIT 10;
您可以在这里找到 working SQL Fiddle example 。