您可以操作查詢以使用SUM(criteria)
或SUM(IF(condition, 1, 0))
來分別對每列進行計數。
SELECT
SUM(rslat = 'severe') as rslat_count,
SUM(rselbow = 'severe') as rselbow_count,
SUM(rsmed = 'severe') as rsmed_count,
SUM(rscentral = 'severe') as rscentral_count
FROM forearm
WHERE business='zmon'
數據:
| id | business | rslat | rselbow | rsmed | rscentral |
|----|----------|--------|---------|--------|-----------|
| 1 | zmon | severe | severe | severe | good |
| 2 | zmon | severe | severe | good | good |
| 3 | zmon | good | severe | good | good |
| 4 | zmon | severe | severe | good | good |
結果:http://sqlfiddle.com/#!9/093bd/2
| rslat_count | rselbow_count | rsmed_count | rscentral_count |
|-------------|---------------|-------------|-----------------|
| 3 | 4 | 1 | 0 |
然後你可以使用顯示在PHP的結果
$sentence = 'There are %d employees severe in %s';
while ($row = mysql_fetch_assoc($result)) {
printf($sentence, $row['rslat_count'], 'rslat');
printf($sentence, $row['rselbow_count'], 'rselbow');
printf($sentence, $row['rsmed_count'], 'rsmed');
printf($sentence, $row['rscentral_count'], 'rscentral');
}
已更新
要獲得各列的派生總數,只需將它們相加即可。
SELECT
SUM(counts.rslat_count + counts.rselbow_count + counts.rsmed_count + counts.rscentral_count) as severe_total,
counts.rslat_count,
counts.rselbow_count,
counts.rsmed_count,
counts.rscentral_count
FROM (
SELECT
SUM(rslat = 'severe') as rslat_count,
SUM(rselbow = 'severe') as rselbow_count,
SUM(rsmed = 'severe') as rsmed_count,
SUM(rscentral = 'severe') as rscentral_count
FROM forearm
WHERE business='zmon'
) AS counts
結果http://sqlfiddle.com/#!9/093bd/10
| severe_total | rslat_count | rselbow_count | rsmed_count | rscentral_count |
|--------------|-------------|---------------|-------------|-----------------|
| 8 | 3 | 4 | 1 | 0 |
然後顯示嚴重總
$sentence = 'There are %d employees severe in %s';
while ($row = mysql_fetch_assoc($result)) {
printf($sentence, $row['rslat_count'], 'rslat');
printf($sentence, $row['rselbow_count'], 'rselbow');
printf($sentence, $row['rsmed_count'], 'rsmed');
printf($sentence, $row['rscentral_count'], 'rscentral');
echo 'business in ' . $row['severe_total'] . ' severe conditions';
}
如果你想獲得所有狀態的計數,還可以使用不同的查詢。 – fyrye
感謝你。我現在意識到我的問題沒有完全表達。我需要加總前臂手腕的數量。 – Paul
@Paul簡單的調整 - 更新,雖然你也可以通過PHP總計各個列來顯示每個列。 – fyrye