Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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;

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

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

Calculating last 15 numbers give you this:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
173 views
Welcome To Ask or Share your Answers For Others

1 Answer

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...