How to add everything in MYSQL

Asked

Viewed 369 times

4

How do I sum everything from a table in Mysql for example..

I have the table tb_comment, then I want to add in each post(id_mark) the amount of rate it will have in total.

For example the id_user 20 has the rate of 4 in id_mark 10 and the id_user 21 has the rate of 5 in id_mark 10 and will give 9 to total as I do to select this in PDO ?

Tabela:

2 answers

7


Mysql has the function SUM( ), suitable for your need.

Here I am grouping by id_user, but can be by another field, depends on the goal:

SELECT SUM(rate) AS total GROUP BY id_user

If you want to add everything up, regardless of id_user, this is enough:

SELECT SUM(rate) AS total

In both cases, the AS total is what gives the name of the field you will use to retrieve the result. Note that you should put a name that does not conflict with any column already existing in the table.

Update: according to your comment, if you want a user just that:

SELECT SUM(rate) AS total WHERE id_user = (id do usuario desejado)

does not even need GROUP BY in this case.

  • Is that correct?: SELECT id_mark, SUM(rate) as rate FROM tb_comment GROUP BY id_mark WHERE id_mark=:post_id

  • or would that be??:: SELECT SUM(rate) AS total GROUP BY id_user WHERE id_mark=:post_id

  • and for me to select for example all values of id_mark only counting as '1' each value?? and not 7 as it is in the image

  • @Williamalvares did not get it right. If you want to know only the number of lines, you can use COUNT()

  • Yes only the number of lines.. Can you give me an example ?

  • 1

    SELECT COUNT(*) AS lines, SUM(rate) AS total FROM tb_comment WHERE id_user = .....

Show 1 more comment

2

Browser other questions tagged

You are not signed in. Login or sign up in order to post.