2016-07-06 62 views
0

這裏前n記錄組是我的表例如:如何獲得通過通配符

+--------+-------------+ 
| 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

向我們顯示您當前的查詢嘗試。 – jarlh

+0

我試過這個查詢選擇id,city_detail從tble_name在哪裏(city_detail像'%coi%'或者city_detail像'%hyd%'或者city_detail像'%blr%')order by id desc –

回答

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;