在 MySQL 中计算变量并限制它? [英] Count variable and LIMIT it in MySQL?

查看:47
本文介绍了在 MySQL 中计算变量并限制它?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有下表,其中 'myvariable' 的一些结果是 1,有些不是.我在 PHP 中使用此代码:

I have the following table where some results of 'myvariable' are 1 and some not. I using this code in PHP:

$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;

如您所见,我需要计算 (1+1+1+1) 并在 mytable 中获得此myvariable"的最终结果,但仅针对最后 15 行,而不针对整个表.如何做到这一点?

As you see, I need to count (1+1+1+1) and get final result of this 'myvariable' in mytable but only for the last 15 rows, not for full table. How to do that?

更新,我可以得到这个结果:

Update, I can get this result:

myvariable:

1

0

1

1

1

0

0

0

0

1

0

0

0

1

0

但我不需要那个.我只需要一个数字,在这种情况下 myvariable 的数量必须是 6.

But I don't need that. I need only ONE number and that number of myvariable in this case must be 6.

计算最后 15 个数字给你这个:

Calculating last 15 numbers give you this:

(1+0+1+1+1+0+0+0+0+1+0+0+0+1+0)=6

(1+0+1+1+1+0+0+0+0+1+0+0+0+1+0)=6

仅针对最后 15 行,而不是整个表格的结果.

Only for last 15 rows not a result from whole table.

推荐答案

您可以使用子查询将您正在处理的行数限制为 15,然后对该子查询的结果执行计数:-

You can use a sub query to limit the number of rows you are dealing with to 15, and then perform the count on the result of that sub query:-

SELECT COUNT(*)
FROM
(
    SELECT * 
    FROM mytable 
    WHERE myvariable='1' 
    ORDER BY id desc 
    LIMIT 15
) sub0

我不确定在将行数限制为 15 之前或之后是否要根据 myvariable 排除行,因此您可能希望将 WHERE 子句移到子查询之外.

I am not sure if you want to exclude rows based on myvariable before or after you limit the rows to 15 so you might want to move the WHERE clause outside of the sub query.

这篇关于在 MySQL 中计算变量并限制它?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆