我正在尝试生成元素列表:
- 红色的
- 绿色
- 橙
- 蓝色的
- 黄色+
在这种情况下,橙色被选中,并且我有之前的两个元素和之后的两个元素。
如何从 MySQL 查询中获取此列表?
表格示例:
5 - 一个
1 - 乙
4 - C
8-D
7 - 乙
9 - F
3 - 克
我正在尝试生成元素列表:
在这种情况下,橙色被选中,并且我有之前的两个元素和之后的两个元素。
如何从 MySQL 查询中获取此列表?
表格示例:
5 - 一个
1 - 乙
4 - C
8-D
7 - 乙
9 - F
3 - 克
它应该工作:
SELECT id, color FROM colors WHERE id = (SELECT @i:=(id - 2)
FROM colors
WHERE color = 'orange')
UNION ALL
SELECT id, color FROM colors WHERE id = @i + 1
UNION ALL
SELECT id, color FROM colors WHERE id = @i + 3
UNION ALL
SELECT id, color FROM colors WHERE id = @i + 4;
我终于用应用程序代码做到了:
def get_list_queryset(self):
STEP = 5
LIST_SIZE = 2*STEP+1
current_object = self.get_object()
query_set = list(self.model.objects.order_by(*self.model._meta.ordering))
index = query_set.index(current_object)
# Index too close to start
if index < STEP:
start_ind = 0
end_ind = LIST_SIZE # We don't care if it's too big.
# Index too close to end
elif index+STEP >= len(query_set):
end_ind = len(query_set)
start_ind = end_ind>=LIST_SIZE and end_ind-LIST_SIZE or 0
else:
start_ind = index-STEP
end_ind = start_ind+LIST_SIZE
return query_set[start_ind:end_ind]
答案是 MySQL 不好处理,所以在应用程序中更灵活。
如果您的基础中的每个元素都有一个 ID,则可以执行以下操作:
SELECT element FROM table
WHERE id BETWEEN (select (id - 2) from table where element = "orange") AND (select (id + 2) from table where element = "orange")