MySQL全部选择范围内的行

时间:2016-08-08 17:42:48

标签: php mysql

我需要一些帮助从范围内的行中检索数据。 让我们说这是我的表:

enter image description here

这就是我需要的:

我需要按ID对行进行排序,然后获取 9 行,其中 gameID 1 获胜者 unique_id 必须在中间。 例如:

$gameID = 1;
$winner = "iii";

所以它应该返回:

5.eee
6.fff
7.ggg
8.hhh
9.iii <--- winner in the middle
10.jjj
11.kkk
12.lll
13.mmm

如何实现这一结果?

感谢。

编辑:

$b = $db->query("SELECT * FROM test WHERE gameID = 1 AND unique_id = 'iii'");
$res = $b->fetch();
$winnerID = $res['ID'];
$b2 = $db->query("SELECT * FROM test WHERE ID BETWEEN $winnerID-4 AND $winnerID+4 ORDER BY ID ASC");
$data = $b2->fetchAll();

这很有效,但我想知道它是否可能在一行中。

1 个答案:

答案 0 :(得分:1)

这是你正在寻找的吗?

首先找到获胜者的ID,然后选择ID小于且大于4的行。(4 + 4 + 1 = 9)

proc sort data=have;
  by city date;
run;

proc transpose data=have out=have_t;
  by city date;
  var var1-var3;
run;

proc sort data=have_t;
  by city _name_ date;
run;

data want;
  set have_t;
  by city _name_ date;
  retain first_nonmiss;
  where not missing(col1);
  if first._name_ then do;
    first_nonmiss = date;
  end;
  if last._name_ then do;
    last_nonmiss = date;
    output;
    call missing(of first_nonmiss);  *I like to do this for safety even though it is irrelevant here - later code might make it relevant;
  end;
run;

Example