简体   繁体   English

根据字段值计算num_rows

[英]Count num_rows base on field value

*The actual problem is quite more complex than the post title :S *实际问题比帖子标题复杂得多: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 通过特定的表决ID查询表
  2. Then Count how many voted up and how many voted down from the query in 1 再算上多少投多少从查询中1 否决
  3. Then I want to check also that had John voted for that vote_id or not. 然后,我还想检查一下约翰是否投票给了vote_id。

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 但是有一种方法(等效代码)无需使用WHILE LOOP即可执行此操作,因为实际表可能非常大,因此运行while循环可能非常详尽:

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. 将根据John的投票方式返回包含updownNULL的行。 Assuming he can only vote once... 假设他只能投票一次...

Note that adding indexes on vote_type and maybe vote_user will help performance. 请注意,在vote_type或也许vote_user上添加索引将有助于提高性能。

You can run this query to give you a table of votes up and down for a specific vote_id. 您可以运行此查询为您提供特定表决_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 我将运行另一个查询来检查约翰是否投票给了vote_id

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) 或总和的任何变化(当情况下)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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