我试图限制用于在 SQL 中进行计算的行数;
SELECT SUM(`position`)/COUNT(`id`) AS `avg`
FROM rankings_04_06_13
WHERE site_id = '7'
ORDER BY `position` ASC
LIMIT 4
但是,当我这样做并不会改变答案时,就好像计算在到达 LIMIT 和 ORDER BY 子句之前已经发生了一样。
有任何想法吗?
试试这个(就像@DekDekku 建议的那样):
SELECT
SUM(`position`)/COUNT(`id`) AS `avg`
FROM (
SELECT `position`,
`id`
FROM rankings_04_06_13
WHERE site_id = '7'
ORDER BY `position` ASC
LIMIT 4
) as tmp
更新:要限制 75% 的行,你可以试试这个(但效率不高):
SET @c:=0;
SELECT
SUM(`position`)/COUNT(`id`) AS `avg`
FROM (
SELECT
`position`,
`id`,
@c:=@c+1,
MOD(@c,4) as m
FROM
rankings_04_06_13
WHERE
site_id = '7'
) as tmp
WHERE
m <> 3
这是一个使用派生表的示例。这可能是您要查找的内容,具体取决于您要如何应用限制(您可能希望group by position
获得前 4 个位置而不是前 4 行)
SELECT SUM(`position`)/COUNT(`id`) AS `avg`
FROM (SELECT position, id
FROM rankings_04_06_13
WHERE site_id = '7'
ORDER BY `position` ASC
LIMIT 4
) AS AVRG
试试这个
SELECT SUM(`position`)/COUNT(`id`) AS `avg`
FROM (SELECT position,id from rankings_04_06_13
WHERE site_id = '7'
ORDER BY `position` ASC LIMIT 4) as t2
SELECT SUM(`position`)/COUNT(`id`) AS `avg`
FROM (SELECT postion,id from rankings_04_06_13
WHERE site_id = '7'
ORDER BY `position` ASC LIMIT 4) AS subquery;