Group results in MYSQL applying inner join

2

I'm trying to group 3 related tables this would be the sql code

SELECT *
FROM metadata_values mvalues
INNER JOIN metadata_descriptors mdes ON mdes.idDescriptor = mvalues.idDescriptor
INNER JOIN metadata_schemas mschema ON mschema.idSchema = mdes.idSchema

It brings all the results but what I'm looking for is to group them.

    
asked by Arielperez 21.08.2018 в 22:14
source

1 answer

1

The final result to group them in a JOIN can be like this

SELECT *
FROM metadata_values mvalues
INNER JOIN metadata_descriptors mdes ON mdes.idDescriptor = mvalues.idDescriptor
INNER JOIN metadata_schemas mschema ON mschema.idSchema = mdes.idSchema
GROUP BY mvalues.names ASC;
  

Simply at the end of your query, place the GROUP BY() statement and indicate the name of the table and column you want to be the   reason for grouping

     

As notes in the example that I put grouped by the name of the table   which is called mvalues, which will achieve that if there is more than one record   with the same name, group them, incidentally, the sentence in question works with the grouping sentences; which are max, min, sum, avg, etc

EXAMPLE

By using a sequence with JOIN, I obtain the data of the users and their posts made; in this way

MariaDB [blog]> SELECT users.nameUser, posts.namePost
    -> FROM users JOIN posts ON users.idUser = posts.user_id
    -> ;

MY RESULT IS

+----------+----------+
| nameUser | namePost |
+----------+----------+
| alfa     | PHP-7    |
| beta     | HTML-5   |
| beta     | MYSQL-8  |
| alfa     | aire     |
+----------+----------+

Using the GROUP BY statement and the count () aggregation function, I'll only get the grouped users and the total of each one's posts

MariaDB [blog]> SELECT users.nameUser, posts.namePost, COUNT(posts.namePost)
    -> FROM users JOIN posts ON users.idUser = posts.user_id
    -> GROUP BY users.nameUser;

this is my result

+----------+----------+-----------------------+
| nameUser | namePost | COUNT(posts.namePost) |
+----------+----------+-----------------------+
| alfa     | PHP-7    |                     2 |
| beta     | HTML-5   |                     2 |
+----------+----------+-----------------------+
    
answered by 21.08.2018 / 22:18
source