Reputation: 7278
*The actual problem is quite more complex than the post title :S
Suppose I have table
ID | vote_id | vote_type | vote_user
1 ---- 2 ----- up ------- Tom
2 ---- 3 ----- up ------- John
3 ---- 3 ----- down ----- Harry
4 ---- 4 ----- up ------- Tom
5 ---- 2 ----- down ----- John
6 ---- 3 ----- down ----- Tom
So what I want to do is
And the way I do is.
$up=0;
$down=0;
$voted="no";
$r=mysql_query("SELECT*FROM table_name WHERE vote_id == 3");
while($row=mysql_fetch_array($r){
if($row["vote_type"]=="up"){ $up++;}else{$down++;}
if($row["vote_user"=="John"){ $voted="yes";}
}
But is there a way ( equivalent code ) to do this without using WHILE LOOP because the actual table can be very large so running while loop can be very exhaustive :S
EDIT Can I do with single query?
Upvotes: 2
Views: 126
Reputation:
Use two separate queries:
Count all votes:
SELECT vote_type, COUNT(*) AS amount
FROM table_name
WHERE vote_id = 3
GROUP BY vote_type
will return up to two rows:
vote_type | amount
----------+--------
up | 1
down | 2
Find out if John voted:
SELECT vote_type
FROM table_name
WHERE vote_id = 3
AND vote_user = 'John'
will return a row containing either up
, down
or NULL
based on how John voted. Assuming he can only vote once...
Note that adding indexes on vote_type
and maybe vote_user
will help performance.
Upvotes: 1
Reputation: 86765
In a single query
Select
sum(case when vote_type = 'up' then 1 else 0 end) as up,
sum(case when vote_type = 'down' then 1 else 0 end) as down,
sum(case when vote_user = 'john' then 1 else 0 end) as john
from
yourTable
where
vote_id = 3
Or any variation of sum(case when)
Upvotes: 0
Reputation: 5701
You can run this query to give you a table of votes up and down for a specific vote_id.
select vote_type, COUNT(*) from votes where vote_id = 2 AND group by vote_type
I would run another query to check to see if John voted for that vote_id or not
select count(*) from votes where vote_id = 2 AND vote_user = 'John'
Upvotes: 0