简体   繁体   English

如何在PHP-MySQL上获取具有一定值的字段总数

[英]How to get the total number of fields with a certain value on PHP-MySQL

I have 20 columns named as qa1, qa2, qa3 up to qa20 which will hold the value of either YES or NO . 我有20列,分别命名为qa1, qa2, qa3 up to qa20 ,它们将保存YESNO的值。 How would I get the number of columns that holds the value of YES and the number of columns that hold the value of NO . 如何获取保存YES的列数和保存NO的列数。

Addition: The table description is like this: 另外:表描述是这样的:

examid int,
firstname varchar(20),
middlename varchar(20),
lastname varchar(20),
q1 varchar(1),
q2 varchar(1), .... up to q20(1)

For ex. 对于前。 The test data would be 测试数据将是

q1 = y
q2 = n
q3 = y
q4 = n
q5 = y
q6 = n
q7 = y
q8 = n
q9 = y
q10 = y

I would like to get: 我想得到:

answer for y = 6 answer for n = 4 y = 6答案n = 4答案


I figured it out, using php and mysql I came to: 我想通了,使用php和mysql我来到:

$yescounter = 0;
$nocounter = 0;
for($x1 = 1; $x1<= 20; $x1++){
$trial1 = mysql_query("SELECT qanswer$x1 FROM tb_erm_exam_results WHERE qanswer$x1='y'");
$t1 = mysql_num_rows($trial1);
if($t1 == 1) { $yescounter++; } else { $nocounter++; }
}
echo "YES is: ".$yescounter." while NO is:".$nocounter;

which just gives the same result but without complicated mysql queries. 只是给出了相同的结果,但没有复杂的mysql查询。

SELECT id, (qa1 = 'Y' + qa2 = 'Y' + ... + qa20 = 'Y') AS yes_count,
           (qa1 = 'N' + qa2 = 'N' + ... + qa20 = 'N') AS no_count
FROM yourtable

As you can see, structuring your table this way makes queries like this complicated. 如您所见,以这种方式构造表会使诸如此类的查询变得复杂。 It would be better if you used a table where each answer was in a different row. 如果使用每个答案都在不同行中的表,那会更好。 Then you could do 那你可以做

SELCT id, SUM(qa = 'Y') AS yes_count, SUM(qa = 'N') AS no_count
FROM yourTable
GROUP BY id

This table would be structured like: 该表的结构如下:

CREATE TABLE yourTable (
    id INTEGER NOT NULL, -- Survey ID
    question_num INTEGER NOT NULL, -- 1 to 20
    qa CHAR(1), -- Y or N
    UNIQUE KEY (id, question_num)
)

试试这给我的结果。

select count(*) from sample where  'yes' IN (q1,q2,q3,q4,q5,q6,q7,q8,q9......)

I came to this solution after an hour of trials, It produce the result without using much queries. 经过一个小时的试用,我来到了这个解决方案,它无需太多查询即可产生结果。

$yescounter = 0;
$nocounter = 0;
for($x1 = 1; $x1<= 50; $x1++){
$answercounter1 = mysql_query("SELECT qanswer$x1 FROM tb_erm_exam_results WHERE qanswer$x1='y'");
$ac1 = mysql_num_rows($answercounter1);
if($ac1 == 1) { $yescounter++; } else { $nocounter++; }
}

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

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