MySQL select statement returning results in circle mode

给你一囗甜甜゛ 提交于 2020-05-16 10:57:55

问题


i am working with an app that via swipes you can see cards one after the other. Both left and right swipes are permitted. If the user swipes right he will see the next available card. If he swipes at the left he will see the previous card.

The cards details are stored to a MySQL table 'Cards' and have a unique id let's say 'CardID' starting from number 1.000.000 and so on. Let's say that i currently have added 500 cards to the 'Cards' table, so the last card ID stored is 1.000.500. I want to create a procedure that will send back to the user 20 cards at a time depending on the direction he keeps swipping. If the swipes are done to the left the procedure will send the previous 20 records and so on.

Now think that the user keeps swipping left and requests the previous records from number 1.000.009 and below. I want to write a select statement that will fetch and serve to the user those 9 rows left and the 11 rows from the bottom of the table alltogether. That would be records with CardID 1.000.489 to 1.000.500, so as the user swipes, when he will swipe no 1.000.000 (the first) he will go by circle to see 1.000.500 and vice versa

Thank you in advance


回答1:


DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table (id SERIAL PRIMARY KEY);

INSERT INTO my_table VALUES 
(1),
(2),
(3),
(4),
(5),
(6),
(7),
(8),
(9);

SELECT * FROM my_table ORDER BY id > 5 DESC, id;
+----+
| id |
+----+
|  6 |
|  7 |
|  8 |
|  9 |
|  1 |
|  2 |
|  3 |
|  4 |
|  5 |
+----+


来源:https://stackoverflow.com/questions/60040212/mysql-select-statement-returning-results-in-circle-mode

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!