sql >> Base de Datos >  >> RDS >> Mysql

MySQL Group_Concat () frente a T-SQL String_Agg ()

Una de las funciones de T-SQL introducidas en SQL Server 2017 es STRING_AGG() función. Esto es básicamente el equivalente de GROUP_CONCAT() de MySQL función:le permite devolver los resultados de la consulta como una lista delimitada, en lugar de filas.

Pero hay algunas diferencias menores entre las dos funciones.

Este artículo explora algunas de las principales diferencias de sintaxis entre estas funciones.

Sintaxis

En primer lugar, aquí está la sintaxis oficial de cada función.

MySQL – GRUPO_CONCAT()

GROUP_CONCAT([DISTINCT] expr [,expr ...]
             [ORDER BY {unsigned_integer | col_name | expr}
                 [ASC | DESC] [,col_name ...]]
             [SEPARATOR str_val])

T‑SQL:STRING_AGG()

STRING_AGG ( expression, separator ) [ <order_clause> ]

<order_clause> ::=   
    WITHIN GROUP ( ORDER BY <order_by_expression_list> [ ASC | DESC ] )

Diferencias de sintaxis

Estas son las tres principales diferencias de sintaxis entre GROUP_CONCAT() de MySQL y STRING_AGG() de T-SQL funciones:

  • Separador predeterminado :Probablemente la diferencia más obvia es el hecho de que STRING_AGG() requiere que especifique un separador. Si no proporciona dos argumentos (el segundo de los cuales es el separador), obtendrá un error. Con GROUP_CONCAT() de MySQL por otro lado, el separador es un argumento opcional. Si no lo proporciona, utilizará una coma de forma predeterminada.
  • Ordenar los resultados :mientras que las funciones de MySQL y T-SQL le permiten agregar un ORDER BY cláusula, la sintaxis es ligeramente diferente. T-SQL requiere que uses el WITHIN GROUP cláusula al ordenar el conjunto de resultados, mientras que MySQL no tiene este requisito.
  • Resultados distintos :MySQL le permite usar DISTINCT para devolver solo valores únicos. T-SQL no ofrece esta opción.

A continuación hay ejemplos para demostrar estas diferencias.

Separador predeterminado

MySQL – GRUPO_CONCAT()

No necesitamos especificar el separador en MySQL. Este es un argumento opcional. El valor predeterminado es una coma.

SELECT GROUP_CONCAT(Genre) AS Result
FROM Genres;

Resultado:

+----------------------------------------------+
| Result                                       |
+----------------------------------------------+
| Rock,Jazz,Country,Pop,Blues,Hip Hop,Rap,Punk |
+----------------------------------------------+

T‑SQL:STRING_AGG()

T-SQL requiere que especifiquemos el separador.

SELECT STRING_AGG(Genre, ',') AS Result
FROM Genres;

Resultado:

Result                                      
--------------------------------------------
Rock,Jazz,Country,Pop,Blues,Hip Hop,Rap,Punk

Si no especificamos un separador obtenemos un error:

SELECT STRING_AGG(Genre) AS Result
FROM Genres;

Resultado:

Error: The STRING_AGG function requires 2 argument(s).

Ordenar los resultados

MySQL – GRUPO_CONCAT()

Al ordenar el conjunto de resultados en MySQL, simplemente agregue el ORDER BY cláusula como argumento, seguida de la columna por la que ordenarla, seguida de ASC o DESC dependiendo de si lo quieres en orden ascendente o descendente.

USE Music;
SELECT 
  ar.ArtistName AS 'Artist',
  GROUP_CONCAT(al.AlbumName ORDER BY al.AlbumName DESC) AS 'Album List'
FROM Artists ar
INNER JOIN Albums al
ON ar.ArtistId = al.ArtistId
GROUP BY ArtistName;

Resultado:

+------------------------+----------------------------------------------------------------------------+
| Artist                 | Album List                                                                 |
+------------------------+----------------------------------------------------------------------------+
| AC/DC                  | Powerage                                                                   |
| Allan Holdsworth       | The Sixteen Men of Tain,All Night Wrong                                    |
| Buddy Rich             | Big Swing Face                                                             |
| Devin Townsend         | Ziltoid the Omniscient,Epicloud,Casualties of Cool                         |
| Iron Maiden            | Somewhere in Time,Powerslave,Piece of Mind,No Prayer for the Dying,Killers |
| Jim Reeves             | Singing Down the Lane                                                      |
| Michael Learns to Rock | Scandinavia,Eternity,Blue Night                                            |
| The Script             | No Sound Without Silence                                                   |
| Tom Jones              | Praise and Blame,Long Lost Suitcase,Along Came Jones                       |
+------------------------+----------------------------------------------------------------------------+

T‑SQL:STRING_AGG()

Al ordenar los resultados concatenados con ORDER BY ,  SQL Server requiere que WITHIN GROUP se utilizará la cláusula.

USE Music;
SELECT 
  ar.ArtistName AS 'Artist',
  STRING_AGG(al.AlbumName, ', ') WITHIN GROUP (ORDER BY al.AlbumName DESC) AS 'Album List'
FROM Artists ar
INNER JOIN Albums al
ON ar.ArtistId = al.ArtistId
GROUP BY ArtistName;

Resultado:

Artist                     Album List                                                                    
-------------------------  ------------------------------------------------------------------------------
AC/DC                      Powerage                                                                      
Allan Holdsworth           The Sixteen Men of Tain, All Night Wrong                                      
Buddy Rich                 Big Swing Face                                                                
Devin Townsend             Ziltoid the Omniscient, Epicloud, Casualties of Cool                          
Iron Maiden                Somewhere in Time, Powerslave, Piece of Mind, No Prayer for the Dying, Killers
Jim Reeves                 Singing Down the Lane                                                         
Michael Learns to Rock     Scandinavia, Eternity, Blue Night                                             
The Script                 No Sound Without Silence                                                      
Tom Jones                  Praise and Blame, Long Lost Suitcase, Along Came Jones                        

Resultados distintos

MySQL – GRUPO_CONCAT()

GROUP_CONCAT() de MySQL es compatible con DISTINCT cláusula, que le permite eliminar valores duplicados del conjunto de resultados.

USE Solutions;
SELECT GROUP_CONCAT(DISTINCT TaskName) 
FROM Tasks;

Resultado:

+--------------------------------------------------------+
| GROUP_CONCAT(DISTINCT TaskName)                        |
+--------------------------------------------------------+
| Do garden,Feed cats,Paint roof,Relax,Take dog for walk |
+--------------------------------------------------------+

T‑SQL:STRING_AGG()

STRING_AGG() de T-SQL la función no es compatible con DISTINCT cláusula.

USE Solutions;
SELECT STRING_AGG(DISTINCT TaskName, ',') 
FROM Tasks;

Resultado:

Error: Incorrect syntax near ','.

Como era de esperar, se produce un error si intentamos usar DISTINCT cláusula con STRING_AGG() .