mysqlで検索結果を何らかの順序でソートした結果に対して、さらに条件を指定して検索結果を絞り込む方法です。
mysql> select * from tbl3;
+-----+------+-------+
| id | type | score |
+-----+------+-------+
| id0 | O | 0 |
| id1 | B | 2 |
| id2 | A | 4 |
| id3 | AB | 6 |
| id4 | A | 8 |
+-----+------+-------+
5 rows in set (0.00 sec)
scoreの上位3件内で、type='A'のレコードだけを抽出するには
以下のようにします。
ordにはscoreでの順位を取得しています。
mysql> set @ord := 0;
mysql>
select
t.ord
, t.id as id
, t.type as type
, t.score as score
from
(
select
@ord := @ord + 1 as ord
, id as id
, type as type
, score as score
from
tbl3
order by
id desc
limit 3
) t
where
type = 'A'
;
+------+-----+------+-------+
| ord | id | type | score |
+------+-----+------+-------+
| 1 | id4 | A | 8 |
| 3 | id2 | A | 4 |
+------+-----+------+-------+
2 rows in set (0.00 sec)
mysql> select * from tbl3;
+-----+------+-------+
| id | type | score |
+-----+------+-------+
| id0 | O | 0 |
| id1 | B | 2 |
| id2 | A | 4 |
| id3 | AB | 6 |
| id4 | A | 8 |
+-----+------+-------+
5 rows in set (0.00 sec)
scoreの上位3件内で、type='A'のレコードだけを抽出するには
以下のようにします。
ordにはscoreでの順位を取得しています。
mysql> set @ord := 0;
mysql>
select
t.ord
, t.id as id
, t.type as type
, t.score as score
from
(
select
@ord := @ord + 1 as ord
, id as id
, type as type
, score as score
from
tbl3
order by
id desc
limit 3
) t
where
type = 'A'
;
+------+-----+------+-------+
| ord | id | type | score |
+------+-----+------+-------+
| 1 | id4 | A | 8 |
| 3 | id2 | A | 4 |
+------+-----+------+-------+
2 rows in set (0.00 sec)