2013-08-16 88 views
1

我有一個查詢從數據庫打印記錄,但我不明白如何省略某些字段包含零的記錄。可能包含零的字段是townhalls,org_pressconfrep_doorsvol_doors,contacts,phones,coffeehours,newsarticlesmediahits。如果上面提到的每個字段都等於零,我該如何編寫查詢以忽略這些結果?如何省略某些字段中包含零的記錄?

// START Organizer Report 
// sending query 
$result = mysql_query("SELECT 
Concat(last_name, ' , ', first_name) as Representative, 
sum(townhalls) as Townhalls, 
sum(org_pressconf) as PressConference, 
sum(rep_doors) as RepDoors, 
sum(vol_doors) as VolunteerDoors, 
sum(contacts) as Contacts, 
sum(phones) as Phones, 
sum(coffeehours) as CoffeeHours, 
sum(newsarticles) as NewsArticles, 
sum(mediahits) as MediaHits 
FROM reports 
join representatives on reports.rep = representatives.id 
join users on reports.username = users.username 
WHERE date BETWEEN '$from' AND '$to' AND role = 'organizer' 
Group By representative Order By representative;"); 
if (!$result) { 
    die("Query to show fields from table failed"); 
} 


$fields_num = mysql_num_fields($result); 

echo "<h2>Organizer Report <small>($from to $to)</small></h2>"; 
echo "<table border='1' cellspacing='0' cellpadding='3' cellspacing='0' cellpadding='3'> 
<tr>"; 

// printing table headers 
for($i=0; $i<$fields_num; $i++) 
{ 
    $field = mysql_fetch_field($result); 
    echo "<td>{$field->name}</td>"; 
} 
echo "</tr>\n"; 

// printing table rows 
while($row = mysql_fetch_row($result)) 
{ 
    echo "<tr>"; 

    // $row is array... foreach(..) puts every element 
    // of $row to $cell variable 
    foreach($row as $cell) 
     echo "<td>$cell</td>"; 

    echo "</tr>\n"; 
} 

mysql_free_result($result); 

    echo "</table>\n"; 
// END Organizer Report 
+3

'WHERE townhalls!= 0 AND ...!= 0 AND ...'? –

+0

'HAVING Townhalls> 0 AND PressConference> 0 AND ...' –

+1

我認爲在GROUP BY之前進行過濾(使用WHERE)會是更有效的變體,因爲它會減少要檢查的行數分組。 –

回答

0

如果您想忽略所有這些字段都等於零的行,請添加以下HAVING子句。

HAVING (townhalls + org_pressconf + rep_doors + vol_doors + contacts + phones + coffeehours + newsarticles + mediahits) > 0 
相關問題