计算MySQL中的限制变量?

时间:2014-11-27 02:50:02

标签: mysql limit counting

没有人能回答这个问题?

$result=mysql_query("
SELECT COUNT(*) AS `total` FROM `mytable` 
WHERE `myvariable`='1' 
ORDER BY `id` DESC 
LIMIT 15;"
);

$data=mysql_fetch_array($result);

$count = $data['total'];

echo $count;

这计算来自mytable的所有结果,但我怎样才能计算最后15个结果?看来LIMIT 15在这种情况下不起作用?

2 个答案:

答案 0 :(得分:1)

我认为这是您想要的查询:

SELECT SUM(myvariable = '1') AS total
FROM (SELECT myvariable
      FROM mytable
      ORDER BY id DESC
      LIMIT 15) AS subquery

这仅查看最近的15行,并计算具有myvariable = 1的行数。

答案 1 :(得分:0)

由于您希望按降序排列最后15,因此按升序排序并选择前15并按降序排序

select * from (SELECT *  FROM mytable WHERE myvariable='1' ORDER BY id ASC LIMIT 15) ORDER BY  id DESC