我很难创建一个 MySql 查询,它将逐行搜索一个表,然后在每一侧返回 5 个周围的行。
问题是行是按字母顺序排列的,我们不能使用 id 字段
基本上,重点是获得 11 行,当前行正好位于中间,同时按字母顺序排列。
这真的很容易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
所以你想选择一系列行,row_number 应该是你的朋友,因为你说你不能依赖 id。检查这个被广泛接受和详细的SO answer about the use of mySQL ROW_NUMBER
.
然后试试这个有效的SQL Fiddle 代码。但是我仍在对其进行一些调整,因为它确实通过设置行上的值来恢复您需要的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
如果您的表中没有太多记录,您可以使用临时表来解决它:
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
根据您的参数尝试如下:
SELECT * FROM table WHERE id < 5 LIMIT 10
UNION
SELECT * FROM table WHERE id = 5
UNION
SELECT * FROM table WHERE id > 5 LIMIT 10;