[英]How to use the result of a select as offset in an SQL query
I was trying to create a single SQL query to return what I need, instead of creating 2 querys, but I need to use the result of one of the querys as the offset
of the other one. 我试图创建一个单独的SQL查询来返回我需要的内容,而不是创建2个查询,但我需要使用其中一个查询的结果作为另一个查询的
offset
。
My table has user answers with scores, each user may have multiple answers in that table. 我的表有用户答案和分数,每个用户可能在该表中有多个答案。 And I want to calculate the middle point of the table of ordered scores.
我想计算有序分数表的中间点。
Example: 例:
User answers: 用户回答:
Ranking Table: 排名表:
Solution: 解:
The first query calculates the middle point: 第一个查询计算中间点:
SELECT CEILING(count(Distinct(id_user)) / 2) as position
FROM us_user_response
where id_round=1
Query result: 查询结果:
position : 2
职位:2
This second query creates the ordered ranking table: 第二个查询创建有序排名表:
SELECT sum(points) as score
FROM us_user_response
where id_round=1
GROUP BY id_user
Order by score DESC
Now I want to create one big query that returns the score of the middle user, I just need to use the first query result as offset
of the second query: 现在我想创建一个返回中间用户得分的大查询,我只需要将第一个查询结果用作第二个查询的
offset
:
SELECT sum(points) as score
FROM us_user_response
where id_round=1
GROUP BY id_user
Order by score DESC LIMIT 1
OFFSET (SELECT CEILING(count(Distinct(id_user)) / 2) as position
FROM us_user_response where id_round=1)
Of course, this doesn't work, is there any way to use a result as offset
? 当然,这不起作用,有没有办法将结果用作
offset
?
EDIT: 编辑:
The queries work nice! 查询效果很好! My question is if there is any way to use the result of a query as the offset of another.
我的问题是,是否有任何方法可以将查询结果用作另一个查询的结果。 So I could accomplish this in one single query.
所以我可以在一个查询中完成此任务。
Try something like this: 尝试这样的事情:
SET @line_id = 0;
SET @line_offset = (
SELECT CEILING(count(Distinct(id_user)) / 2) as position
FROM us_user_response
WHERE id_round = 1
);
SELECT sum(points) as score,
IF((@line_id := @line_id + 1) = @line_offset, 1, 0) AS useit
FROM us_user_response
WHERE id_round = 1
GROUP BY id_user
HAVING useit = 1
ORDER BY score;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.