有没有办法按顺序返回结果?
示例:在quiz
表上运行以下查询:
select q.category_id, q.quiz_id, concat('Quiz ',q.name) name
from quiz q
where q.category_id = 11
order by q.category_id ASC
limit 2
offset 2;
表quiz
(结构):
+-------------+---------+-------+
| category_id | quiz_id | name |
+-------------+---------+-------+
| 10 | 10 | math |
| 11 | 10 | sport | => Quiz Sport 1
| 11 | 11 | sport | => Quiz Sport 2
| 12 | 10 | Geo. |
| 11 | 15 | sport | => Quiz Sport 3
| 11 | 12 | sport | => Quiz Sport 4
| 10 | 17 | math |
| 11 | 20 | sport | => Quiz Sport 5
| 11 | 22 | sport | => Quiz Sport 6
| 10 | 19 | math |
+-------------+---------+-------+
返回:
+-------------+---------+------------+
| category_id | quiz_id | name |
+-------------+---------+------------+
| 11 | 15 | Quiz sport |
| 11 | 12 | Quiz sport |
+-------------+---------+------------+
http://sqlfiddle.com/#!9/110752/2
有没有办法用测验编号顺序返回结果,如下所示:
+-------------+---------+--------------+
| category_id | quiz_id | name |
+-------------+---------+--------------+
| 11 | 15 | Quiz sport 3 |
| 11 | 12 | Quiz sport 4 |
+-------------+---------+--------------+
答案 0 :(得分:2)
您需要建立一个行号来执行此操作。这样做意味着您需要order by
的唯一字段以确保结果的顺序。您可以在mysql中使用user-defined variables
获取行号。以下是quiz_id
重新排序的示例:
select *
from (select q.category_id, q.quiz_id, @rn := @rn + 1, concat('Quiz ',q.name, @rn) name
from quiz q, (select @rn := 0) t
where q.category_id = 11
order by q.category_id ASC, q.quiz_id) t
order by category_id ASC, quiz_id
limit 2
offset 2;
答案 1 :(得分:0)
如果您有主键,可以按主键订购
select q.category_id, q.quiz_id, concat('Quiz ',q.name) name
from quiz q
where q.category_id = 11
order by q.id, q.category_id ASC
limit 2
offset 2;
如果您不建议使用something like this添加主要内容:
ALTER TABLE quiz ADD id INT PRIMARY KEY AUTO_INCREMENT;
如果由于某些原因与您的行为无关, 。您还可以使用上述语句添加PRIMARY
列rank
类似的东西:
auto_increment
(然后运行第一个查询。)
答案 2 :(得分:0)
我发现了一个类似的问题,帮助我找到了你的问题的答案:
(感谢@OMG小马)LINK(请阅读他的答案,以便更多地了解这个问题)
假设您想要按顺序计算测验:
以下是我的回答SQLFiddle link。
基本上,您需要计算条目数,并在列中显示。