限制连接查询的结果

时间:2016-04-20 00:57:29

标签: mysql sql

我有两个表:城市列表和每个城市的类别列表。

Table tv_village

id    | name
--------------
1     | London
2     | Paris


Table tv_village_category

village_id | category   | total
-----------------------------
1          | event      | 10
1          | realestate | 15
1          | job        | 8
1          | place      | 20
2          | event      | 42
2          | realestate | 66
2          | job        | 83
2          | place      | 55

我的问题

我需要获得每个城市的前3个类别(按总数排序)。

我尝试了什么

当我尝试此查询时,它告诉我字段v.id未知是子查询。

    SELECT *
    FROM tv_village v
    INNER JOIN (
        SELECT *
        FROM tv_village_category vc2
        WHERE vc2.village_id = v.id
            AND vc2.total > 0
        ORDER BY vc2.total DESC
        LIMIT 3
    ) vc
    ORDER BY v.id, vc.total DESC

我需要补充一点,表现很重要,我的表格有点大(36K个城市和1M个类别)。

此致

1 个答案:

答案 0 :(得分:0)

一种方法是尝试变量:

select v.*
from (select v.*,
             (@rn := if(@v = village_id, @rn + 1,
                        if(@v := village_id, 1, 1)
                       )
             ) as seqnum
      from tv_village v cross join
           (select @rn := 0, @v := '') params
      order by village, total desc
     ) v
where seqnum <= 3;

这可以利用tv_village(village_id, total)上的索引。