简体   繁体   中英

Count num_rows base on field value

*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

  1. Query the table by specific vote_id
  2. Then Count how many voted up and how many voted down from the query in 1
  3. Then I want to check also that had John voted for that vote_id or not.

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?

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.

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'

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM