2016-06-21 58 views
0

我想做一些statisctics。我的數據庫看起來像這樣:PHP的SQL查詢沒有foreach簡單的方法

+----+------------+------------+------------+--------------+ 
| id | value1  | value2  | value 3 |  year  | 
+----+------------+------------+------------+--------------+ 
| 1 | something1 | something3 | something5 |   2016 | 
| 2 | something2 | something3 | something6 |   2015 | 
| 3 | something1 | something4 | something5 |   2014 | 
| 4 | something1 | something4 | something6 |   2016 | 
| 5 | something2 | something3 | something5 |   2014 | 
+----+------------+------------+------------+--------------+ 

我的問題是如何構建儘可能查詢的查詢,或計算數值,並返回其下方具有結構數組一樣簡單?

[0] => 
    ['year'] => 2014 
    ['value1'] => 
     ['something1'] => 1 
     ['something2'] => 1 
    ['value2'] => 
     ['something3'] => 1 
     ['something4'] => 1 
    ['value3'] => 
     ['something5'] => 2 
[1] => 
    ['year'] => 2015 
    ['value1'] => 
     ['something2'] => 1 
    ['value2'] => 
     ['something3'] => 1 
    ['value3'] => 
     ['something6'] => 1 
[2] => 
    ['year'] => 2016 
    ['value1'] => 
     ['something1'] => 2 
    ['value2'] => 
     ['something3'] => 1 
     ['something4'] => 1 
    ['value3'] => 
     ['something5'] => 1 
     ['something6'] => 1 
+0

'count'會做.. – Fil

+0

地獄,一個循環會做。 – Strawberry

回答

0

這不是一個簡單的查詢:

(
SELECT t2.`year`, 'value1' AS col, t2.value1 AS val_content, COUNT(*) AS total 
FROM YourTable t2 
GROUP BY t2.`year`, t2.value1 
) 
UNION 
(
SELECT t2.`year`, 'value2' AS col, t2.value2 AS val_content, COUNT(*) AS total 
FROM YourTable t2 
GROUP BY t2.`year` , t2.value2 
) 
UNION 
(
SELECT t2.`year`, 'value3' AS col, t2.value3 AS val_content, COUNT(*) AS total 
FROM YourTable t2 
GROUP BY t2.`year` , t2.value3 
) 
ORDER BY 1 , 2 , 3; 

我得到了這樣的結果:

+------+--------+-------------+-------+ 
| year | col | val_content | total | 
+------+--------+-------------+-------+ 
| 2014 | value1 | something1 |  1 | 
| 2014 | value1 | something2 |  1 | 
| 2014 | value2 | something3 |  1 | 
| 2014 | value2 | something4 |  1 | 
| 2014 | value3 | something5 |  2 | 
| 2015 | value1 | something2 |  1 | 
| 2015 | value2 | something3 |  1 | 
| 2015 | value3 | something6 |  1 | 
| 2016 | value1 | something1 |  2 | 
| 2016 | value2 | something3 |  1 | 
| 2016 | value2 | something4 |  1 | 
| 2016 | value3 | something5 |  1 | 
| 2016 | value3 | something6 |  1 | 
+------+--------+-------------+-------+