PHP mysqli选择添加字段

时间:2015-02-19 11:12:34

标签: php mysql mysqli

我有一个看起来像这样的表:

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

我需要一个选择或方式来添加来自特定用户ID的信用

选择将是:

SELECT credit FROM myTable WHERE user_id ='2'

在这种情况下我需要的结果是 500

我该怎么做?

6 个答案:

答案 0 :(得分:2)

在查询中使用SUM()可以解决问题。

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

由于您指定了PHP标记,以下代码将对您有所帮助。

$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'];

答案 1 :(得分:1)

使用sum()

SELECT sum(credit) as sum_credit
FROM myTable
WHERE user_id = 2

答案 2 :(得分:1)

使用聚合函数SUM()

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

详细了解汇总函数here

答案 3 :(得分:1)

您可以通过汇总信用列的总和来完成此操作。查看MySQL reference manual以获取官方说明。

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

使用AS关键字为列指定名称,然后在PHP中,您可以像使用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

答案 4 :(得分:1)

在mysql中尝试SUM()

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

将根据条件

返回匹配的结果总和

答案 5 :(得分:1)

select sum(credit) as total from myTable where user_id = '2'