Mysql获取前后行的数量

时间:2013-02-27 09:53:46

标签: mysql sql

我很难创建一个MySql查询,它将逐行搜索一个表,然后返回每一行周围5行。

问题是行按字母顺序排列,我们不能使用id字段

基本上,关键是要获得11行,当前的行恰好位于中间,而按字母顺序排列。

4 个答案:

答案 0 :(得分:1)

所以你想选择一系列行,row_number应该是你的朋友,因为你说你不能依赖id。请查看广为接受且详细的SO answer,了解mySQL ROW_NUMBER的使用情况。

然后尝试这个工作SQL Fiddle code。但是我还在稍微调整它,因为它确实通过设置WHERE tt.row_number between 3 and 7行上的值来恢复所需的行数,但这些行不是以某种方式选择的行周围。棘手的事情。

测试数据:

id    col1
1    adfg
2    sg5r
3    34tdfgdf
4    ergdfd
5    ghjghghj
6    4gfhfrgfr
7    zxcxvfdf
8    sfdgd
9    s8545454
10    7jhgdfe45
11    fbvmso
12    sdfg9dj3
13    zjvjude89
14    _sdfdi3

查询:

SELECT Table1.* 
  FROM Table1
 WHERE col1 IN (
              SELECT col1
                FROM (SELECT t.col1, 
                             @curRow := @curRow + 1 AS row_number
                        FROM Table1 t
                        JOIN (SELECT @curRow := 0) r
                      ) tt
               WHERE tt.row_number between 3 and 7
             )
ORDER BY col1;

结果数据:

ID  COL1
3   34tdfgdf
6   4gfhfrgfr
4   ergdfd
5   ghjghghj
7   zxcxvfdf

答案 1 :(得分:1)

如果您的表中没有太多记录,您可以使用临时表解决它:

create temporary table temp_yourtable(
    id int auto_increment,
    ....,
    primary key(id)
)
select ... from yourtable;

select t.* from temp_yourtable t, temp_yourtable t1
    where t1.thealpabeticcolumn = your_key and t.id between t1.id - 5 and t1.id + 5

答案 2 :(得分:1)

union非常简单。试试这个:

(select t.* from t where t.col <= YOURNAME
 order by t.col desc
 limit 6
)
union all
(select t.* from t where t.col > YOURNAME
 order by t.col
 limit 5
)
order by t.col

查询的第一部分返回之前的五个。第二个返回五个。

顺便说一下,如果你有重复项,你可能会想要这个:

(select t.* from t where t.col = YOURNAME)
union all
(select t.* from t where t.col < YOURNAME
 order by t.col desc
 limit 5
)
union all
(select t.* from t where t.col > YOURNAME
 order by t.col
 limit 5
)
order by t.col

答案 3 :(得分:-1)

根据您的参数尝试以下内容:

SELECT * FROM table WHERE id < 5 LIMIT 10
UNION
SELECT * FROM table WHERE id = 5
UNION
SELECT * FROM table WHERE id > 5 LIMIT 10;