我有一个看起来像这样的表:
id | user_id | credits
----------------------
1 | 2 | 300
2 | 2 | 200
3 | 4 | 100
我需要一个选择或方式来添加来自特定用户ID的信用
选择将是:
SELECT credit FROM myTable WHERE user_id ='2'
在这种情况下我需要的结果是 500
我该怎么做?
答案 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)
答案 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)
答案 5 :(得分:1)
select sum(credit) as total from myTable where user_id = '2'