我从mysql中提取一些数据并计算匹配的出现次数(看似相当于WHERE foo='bar'
)。但是,当我在PHP中循环数据时,我的计数远低于mysql中的计数。
MYSQL> SELECT COUNT(foo) FROM database.table WHERE foo='bar';
# PHP
while ($response = mysql_fetch_assoc($surveydata)){
if ($response==='bar') {
$bar++;
}
}
数据可能包含一个或多个&
,因此我只想匹配bar
而不是bar & foobar
。我怀疑mysql正在计算bar
和bar & foobar
,而php只计算bar
而不是bar & foobar
。 Php正在返回1210
,并且mysql正在返回1783
,因此手动计算以查看谁是正确的,这是非常实用的...
我google了一下,但是对于“mysql完全匹配”或“mysql完全相同”x,x
感到惊讶这是实际的sql
SELECT COUNT(`race`) FROM `database`.`table` WHERE `completion status`='complete';
和实际的php
mysql_query("SELECT `race`,`etcetera` FROM `database`.`table` WHERE `completion status`='complete';");
$demographics=array(
"race"=>array(
"White"=>array('consented'=>0,'partial'=>0,'completed'=>0),
"Black"=>array('consented'=>0,'partial'=>0,'completed'=>0),
"Hispanic"=>array('consented'=>0,'partial'=>0,'completed'=>0),
"Asian"=>array('consented'=>0,'partial'=>0,'completed'=>0),
"Pacific Islander"=>array('consented'=>0,'partial'=>0,'completed'=>0),
"Multiracial"=>array('consented'=>0,'partial'=>0,'completed'=>0),
"Other"=>array('consented'=>0,'partial'=>0,'completed'=>0)
)
//more
);
while ($dbrecord = mysql_fetch_assoc($surveydata)) {
foreach ( $dbrecord as $dbfield=>$dbcellval ) {
foreach ( $demographics as $demographic=>&$options ) {
foreach ( $options as $option=>&$counter ) {
if ( $option==="Multiracial" && strpos($dbcellval,'&') >0 && strpos($dbcellval,'&')!==false ) {
if ($dbrecord['consent']==="1"){
$demographics["race"]["Multiracial"]['consented']++;
if ($dbrecord['completion status']==="partial") {
$demographics["race"]["Multiracial"]['partial']++;
} // if
else if ($dbrecord['completion status']==="complete") {
$demographics["race"]["Multiracial"]['completed']++;
} // else if
} // if
}
else if ($option===$dbcellval){
if ($dbrecord['consent']==="1"){
$counter['consented']++;
if ($dbrecord['completion status']==="partial") {
$counter['partial']++;
} // if
else if ($dbrecord['completion status']==="complete") {
$counter['completed']++;
} // else if
} // if
} // else if $option==$item
} // foreach $options
} // foreach $demographics
} // foreach $dbrecord
} // while
来自SELECT race FROM database.table
的数据如下:
White & Black
White
White & Asian
White & Asian & Black
Asian
Asian & Black
// etc
答案 0 :(得分:2)
你可以这样做:
MYSQL> SELECT COUNT(foo) FROM database.table WHERE BINARY foo='bar';
BINARY做了魔术!!!
答案 1 :(得分:1)
如果要计算foo
正好bar
的记录,那么您的SQL查询是正确的。
您的PHP代码有问题,您发布的代码根本不起作用(应该计算0条记录)。
答案 2 :(得分:0)
MYSQL> SELECT COUNT(foo)AS FROM FROM database.table WHERE foo ='bar';
$response = mysql_fetch_assoc($surveydata);
echo $response['rows'];