You need to make a request that will calculate and simultaneously display data. For a better understanding of my thoughts, I will provide an example below. There is a table in which there is data

id_post | name 1 | test1_1 1 | test1_2 2 | test2_1 2 | test2_2 2 | test2_3 3 | test3_1 3 | test3_2 

As a result, I need to calculate the same id_post and display the data in this form

 id_post | name 2 | test1_2 3 | test2_3 2 | test3_2 
  • how to choose name? now it is displayed like this, and then it can display them in a different order - BOPOH
  • It is desirable to sort. He cares little for me, because It is not needed for this task. - lolokot
  • 2
    Well, if the name is not needed, then why choose it? you can simply select distinct id_post from table_name , or select id_post, name from table_name group by id_post - mysql allows you to do so without aggregate functions on the name, only it chooses an arbitrary value (it will be more correct to think so than to assume that it chooses the first, if only because that sorting is not explicitly set here) - BOPOH
  • I need to calculate all the same id_post, and not to group. In words, everything is simple: 1) Take all the same id_post 2) calculate them and in the final output show what I indicated in the example - lolokot
  • one
    @lolokot, so if you need to calculate, then it’s necessary to write in the question, it’s just not so clear in the example (it seemed that post_id should be output). Everything is calculated simply: select post_id, count(1) as cnt from table_name group by post_id - as a result, get post_id with its quantity in cnt - BOPOH

2 answers 2

 select count(id_post) as cnt, name from test group by id_post; 

    You need to decide on the sort order of the records, which will give you the correct order of names within the same id, and it should be possible to set the reverse sort. Suppose you have 1 more field with the date, and you need to give the name to the last date, then the query will look like this:

     select count(id_post), name from (select id_post,name from table order by id_post,date desc ) A group by id_post 

    This is because MySQL, when grouping and the absence of an aggregate function, takes from some field the value of this field from the first record in the group.