Mysql is a very nice database. Just like php its extreamly forgiving. Anyone with experience with RDBMS setups will know exactly what we mean. For this article, we will be discussing the “Group By” argument and how mysql makes really good guesses. Moreover, we will be discussing what happens when mysql doesn’t make that guess and you have to learn a little more SQL to generate the results

Scenario

We were looking for the “COUNT” or amount of times, each distinct record in a particular column existed. So in a column of types, what types exist and how many of said type. The type should not be repeated within the result. Under a simple test, we can see that there is absolutely no need for a “Group By” clause

[php]

mysql_query("SELECT TYPE , COUNT( id ) AS amt
FROM equiptable1");

[/php]

This will produce a result with one row. The issue here is that there are too many columns  for mysql to figure out the important aspects. The truth is, in any RDBMS, that query probably won’t work without the “Group By” clause once it gets anymore complex like the following join example. Thats right, you have been ignoring its use because mysql has been helping you. Just like php but thats a topic for another article.

The Solution

Group by is your friend. Take a look at the following query.  It would return one result without a “Group by” within the clause, The simple answer is the following;

[php]

mysql_query("SELECT TYPE , COUNT( id ) AS amt
FROM equiptable1
GROUP BY TYPE HAVING amt>1");

[/php]

Rabbit Hole Depth

Now lets consider the scenario that probably helped you to stumble across this article. You are trying to jump across several tables like a super star, and you need specific results from one. Eurica, now you have the power of the “Group BY” clause, to explain to the database exactly what the focus of your query is. Take a look at the following example

[php]

mysql_query("SELECT equiptable.Type , COUNT( equiptable.id ) AS amt FROM site1table1 as site
left join bp_groups as ggg ON ggg.id = site.group_id
left join equiptable1 as equiptable ON equiptable.SiteNo = site.SiteNo
WHERE site.group_id = ggg.id AND equiptable.id IS NOT NULL AND ggg.id = ".$bp->groups->current_group->id AND amt > 1 ."GROUP BY equiptable.Type");

[/php]

As you can see, we took this code right out of a real installation. We believe in using real world examples, that way you can visualize actually doing this. The point of the example is that the equiptable1 holds the info yet we need to jump across bp_groups and site1table1 to get there.

Conclusion

The point to take away is that the group by clause becomes most useful when you are engaging in multiple joins. What not covered here is how this setups you up for advanced concepts like group_concat().  However, the simple fact is that if you are trying to get details of specific columns, you may not be retreiving the right result because of the lack of “Group By”.

MySQL es una base de datos muy bonito. Al igual que php su extreamly perdonar. Alguien con experiencia con configuraciones RDBMS sabrá exactamente lo que queremos decir. Para este artículo, vamos a debatir el argumento “Group By” y cómo mysql hace conjeturas realmente buenos. Además, analizaremos lo que ocurre cuando mysql no tiene que adivinar y tienes que aprender un poco más SQL para generar los resultados
Escenario
Estábamos buscando el “Conde” o la cantidad de veces, cada registro distinto en una columna concreta existió. Así que en una columna de tipos, qué tipos existen y cuántas de dicho tipo. El tipo no debe repetirse en el resultado. En virtud de una prueba sencilla, podemos ver que no hay ninguna necesidad de una cláusula “Group By”
[php]

mysql_query("SELECT TYPE , COUNT( id ) AS amt
FROM equiptable1");

[/php]

Esto producirá un resultado con una fila. La cuestión aquí es que hay demasiadas columnas para mysql averiguar los aspectos importantes. La verdad es que en cualquier RDBMS, esa consulta probablemente no funcionará sin la cláusula “Agrupar por” una vez que ya obtiene complejo como en el siguiente ejemplo de combinación. Derecho de eso, ha sido ignorando su uso porque mysql ha sido ayudándole. Al igual que php pero eso es un tema para otro artículo.
La solución
El grupo es por tu amigo. Echa un vistazo a la siguiente consulta. Volvería un resultado sin un “Group by” dentro de la cláusula, la respuesta sencilla es la siguiente;
[php]

mysql_query("SELECT TYPE , COUNT( id ) AS amt
FROM equiptable1
GROUP BY TYPE HAVING amt>1");

[/php]

Rabbit Hole Profundidad
ahora permite considerar el escenario que probablemente ayudó a tropezar a través de este artículo. Está intentando saltar a través de varias tablas como una súper estrella y necesita resultados específicos de uno. Eurica, ahora tiene el poder de la cláusula “Group BY”, para explicar la base de datos exactamente lo que el foco de la consulta es. Eche un vistazo en el siguiente ejemplo
[php]

mysql_query("SELECT equiptable.Type , COUNT( equiptable.id ) AS amt FROM site1table1 as site
left join bp_groups as ggg ON ggg.id = site.group_id
left join equiptable1 as equiptable ON equiptable.SiteNo = site.SiteNo
WHERE site.group_id = ggg.id AND equiptable.id IS NOT NULL AND ggg.id = ".$bp->groups->current_group->id AND amt > 1 ."GROUP BY equiptable.Type");

[/php]

Como puede ver, tomamos este derecho de código fuera de una instalación real. Creemos en el uso de ejemplos del mundo real, de este modo se puede visualizar haciendo esto. El punto del ejemplo aún que la equiptable1 contiene la información que necesitamos pasar a través de bp_groups y site1table1 para llegar allí.
Conclusión
El punto para llevar es que la cláusula group by se vuelve más útil cuando estás participando en varias combinaciones. Sin embargo, el hecho simple es que si están tratando de obtener detalles de columnas específicas, puede ser al recuperar el resultado correcto no debido a la falta de “Group By”.

Sign in

Sign Up

Forgotten Password

Cart

Cart

Share