简体   繁体   中英

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 . 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 .

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


I figured it out, using php and mysql I came to:

$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.

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++; }
}

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