如何通过通配符获取前n个记录组

时间:2016-07-06 10:58:13

标签: mysql sql

这是我的表格示例:

+--------+-------------+
| id     | city_detail |
+--------+-------------+
| 1      | 12_hyd_test |
| 2      | 13_blr_test |
| 3      | 15_blr_test |
| 4      | 18_hyd_test |
| 5      | 17_coi_test |
| 6      | 22_coi_test |
| 7      | 62_hyd_test |
| 8      | 72_blr_test |
| 9      | 92_blr_test |
| 10     | 42_hyd_test |
| 11     | 21_coi_test |
| 12     | 82_coi_test |
+--------+-------+-----+

从这个表中,如何使用group by这样的条件来选择这样的

+--------+-------------+
| id     | city_detail |
+--------+-------------+
| 12     | 82_coi_test |
| 11     | 21_coi_test |
| 10     | 42_hyd_test |
| 7      | 62_hyd_test |
| 9      | 92_blr_test |
| 8      | 72_blr_test |
+--------+-------+-----+

在每个城市中,只显示两个结果(%coi%%hyd%或' %blr%')ID DESC

1 个答案:

答案 0 :(得分:0)

可能最简单的方法是使用变量:

select e.*
from (select e.*,
             (@rn := if(@c = substr(city_detail, 4), @rn + 1,
                        if(@c := substr(city_detail, 4), 1, 1
                       )
             ) as seqnum
      from example e cross join
           (select @c := '', @rn := 0) params
      order by substr(city_detail, 4)
     ) e
where rn <= 2;