在进行联接时控制列中显示的值

Controlling what value appears in a column while doing a join

这个有点复杂,希望我能说清楚。

我有两个 table:

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 个查看的网站,但是网站 URL 是在 test_websites 中定义的。由于 http://foo.com 是 test_websites 中的一个条目,所有以 http://foo.com 开头的条目都应计为 "one website." 因此连接基于 LIKE 条件,并且结果中 http://foo.com 正确计数为 3。

所以,问题是我希望 remote_host 成为在以 http://foo.com 开头的视图中出现最多的那些行的条目。在这种情况下,视图 table 中有两行以 http://foo.com 开头,其中 10.0.13.1 作为 remote_host,因此结果应显示 10.0.13.1 remote_host 列,而不是与第一个以 http://foo.com 开头的条目一起出现的 remote_host,就像现在一样。

谢谢。

已更新

请尝试以下更正的查询:

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.