1

I have a table that looks like this:

id | user_id | credits
----------------------
1  | 2       | 300
2  | 2       | 200
3  | 4       | 100

I need a select or way to add the credits from a specific user id

The select would be:

SELECT credit FROM myTable WHERE user_id ='2'

The result I would need in this case would be 500

How can I do this?

Satch3000
  • 47,356
  • 86
  • 216
  • 346
  • 2
    This is a pretty trivial question. Quick googling for "mysql sum column" would have saved you some time and yielded useful results. – Dzhuneyt Feb 19 '15 at 11:21
  • 2
    possible duplicate of [MySql sum elements of a column](http://stackoverflow.com/questions/4586040/mysql-sum-elements-of-a-column) – Dzhuneyt Feb 19 '15 at 11:23

6 Answers6

2

Use SUM() in your query will solve the issue.

SELECT SUM(`credits`) AS `total` FROM `myTable` WHERE `user_id` =2

Since you specify PHP tag, the below code will help you.

$mysqli=mysqli_connect("hostname","username","password","databasename");
$query = "SELECT SUM(`credits`) AS `total` FROM `myTable` WHERE `user_id` =2";
$processquery = $mysqli->query($query);
$result = $processquery->fetch_assoc();
echo $result['total'];
Gunaseelan
  • 2,494
  • 5
  • 36
  • 43
1

Use sum()

SELECT sum(credit) as sum_credit
FROM myTable
WHERE user_id = 2
juergen d
  • 201,996
  • 37
  • 293
  • 362
1

Use aggregate function SUM():

SELECT SUM(credit) as TotalCredit
FROM myTable 
WHERE user_id='2'

Read more about aggregate functions here.

Raging Bull
  • 18,593
  • 13
  • 50
  • 55
1

You can do this by summing the total of the credit column. Check out the MySQL reference manual for the official instructions.

SELECT SUM(credit) AS credit_total
FROM myTable
WHERE user_id = 2

You use the AS keyword to assign a name to your column, then in PHP you can access this column as you would any other by name, just using credit_total. E.g:

$query = "SELECT SUM(credit) AS credit_total
    FROM myTable
    WHERE user_id = 2";
$result = $mysqli->query($query);
$row = $result->fetch_assoc();
echo $row['credit_total']; // Will output 500
Styphon
  • 10,304
  • 9
  • 52
  • 86
1

Try SUM() in mysql

SELECT SUM(credit) as totalcredit FROM myTable WHERE user_id ='2'

will return you matched result sum according to condition

Rakesh Sharma
  • 13,680
  • 5
  • 37
  • 44
1
select sum(credit) as total from myTable where user_id = '2'
Shailesh Katarmal
  • 2,757
  • 1
  • 12
  • 15