MySQL multiple COUNT cu randuri cu aceeasi valoare

Discutii despre script-uri si coduri PHP-MySQL, precum si lucru cu XML in PHP.
sterica
Mesaje: 285

MySQL multiple COUNT cu randuri cu aceeasi valoare

Salutare,

Am urmatorul tabel sql:

Cod: Selectaţi tot

+-------+---------------+
| STARE |    MENTIUNI   |
+-------+---------------+
|    1  |     men_1     |
|    1  |     men_1     |
|    2  |     men_1     |
|    1  |     men_2     |
|    0  |     men_3     |
+-------+---------------+
si urmatoarele variabile:

Cod: Selectaţi tot

$meniunea1 = '%men_1%';
$meniunea2 = '%men_2%';
$meniunea3 = '%men_3%';
Cum pot interoga tabelul ca sa structurez mentiunile si sa imi contorizeze cate sunt de stare1, stare2 si stare0:

Cod: Selectaţi tot

+-----------+---------+---------+---------+
| MENTIUNEA | STARE_1 | STARE_2 | STARE_0 |
+-----------+---------+---------+---------+
|     men_1 |    2    |     1   |   -     |
|     men_2 |    1    |     -   |   -     |
|     men_3 |    -    |     -   |   1     |
+-----------+---------+---------+---------+

Cod: Selectaţi tot

//contorizez de cate ori apare men_1
$sql = "SELECT * FROM tbl WHERE MENIUNI = $meniunea1";
$res = mysql_query($sql);
echo $num_men = mysql_num_rows($res); //2

//contorizez de cate ori apare stare_1 pentru men_1
$sql = "SELECT * FROM tbl WHERE MENIUNI = $meniunea1 AND STARE = 1";
$res = mysql_query($sql);
echo $num_men = mysql_num_rows($res); //2

si tot asa pentru fiecare variabila si stare
Cum pot evita o repetare a codului ?

Multumesc!

MarPlo Mesaje: 4343
Salut
Vezi daca iti sunt de folos aceste instructini SQL.

Tabel sql:

Cod: Selectaţi tot

+-------+---------------+
| STARE |    MENTIUNI   |
+-------+---------------+
|    1  |     men_1     |
|    1  |     men_1     |
|    2  |     men_1     |
|    1  |     men_2     |
|    0  |     men_3     |
+-------+---------------+
1. SQL 1, cu valori de verifiare puse la coloana STARE:

Cod: Selectaţi tot

select MENTIUNI,
  sum(case when STARE =1 then 1 else 0 end) STARE_1,
  sum(case when STARE =2 then 1 else 0 end) STARE_2,
  sum(case when STARE =0 then 1 else 0 end) STARE_0
from tbl group by MENTIUNI order by MENTIUNI
- Rezultat:

Cod: Selectaţi tot

MENTIUNI STARE_1 STARE_2 STARE_0
 men_1  	2     	1   	0
 men_2  	1     	0   	0
 men_3  	0     	0   	1
2. SQL 1, cu valori de verifiare puse la coloana MENTIUNI:

Cod: Selectaţi tot

select STARE,
  sum(case when MENTIUNI ='men_1' then 1 else 0 end) m_1,
  sum(case when MENTIUNI ='men_2' then 1 else 0 end) m_2,
  sum(case when MENTIUNI ='men_3' then 1 else 0 end) m_3
from tbl group by STARE order by MENTIUNI
- Rezultat:

Cod: Selectaţi tot

STARE m_1 m_2 m_3 	
 1 	 2   1   0
 2 	 1   0   0
 0 	 0   0   1

sterica Mesaje: 285
Multumesc mult de ajutor, functioneaza

Subiecte similare