计算多个字段

时间:2013-05-28 21:51:22

标签: php mysql pdo

我有一张名为reservations的表格。我想计算所有firstNameguestFirstName字段。

我试过了:

$records = $dbh->query('SELECT count(firstName, guestFirstName) from reservations')->fetchColumn;

这给了我一个错误。我如何计算所有firstName, guestFirstName条记录?

2 个答案:

答案 0 :(得分:1)

尝试以下方法:

$query =  'SELECT count(firstName) + count(guestFirstName) as total ' . 
                 'FROM reservations';
$result = $dbh->query($query)->fetch();

echo $result['total']

SQL小提琴验证:http://www.sqlfiddle.com/#!2/42bad/2

SQL的COUNT()函数不计算NULL个值。

感谢@ChaotiCc的帮助

答案 1 :(得分:1)

您需要count()每列,更改如下

'SELECT count(firstName) as total_firstname, count(guestFirstName) as guest_firstname from reservations'