-1

你好,我可以将这两个查询合并到一个查询中吗?我的第一个查询获取数据库中的文章数量,第二个查询获取所有文章的所有访问的总和什么是使其成为一个查询的最佳方法

$stmt = $db->query('SELECT * FROM stories');
$story_count = $stmt->rowCount();

$stmt = $db->query("SELECT sum(visits) FROM stories");
$total_visits = $stmt->fetchColumn();
4

4 回答 4

1

试试喜欢

$stmt = $db->query('SELECT COUNT(*) as total_cnt,
                   SUM(visits) as total_visits FROM stories');

然后执行您的查询,您将从“total_cnt”和“total_visits”获得结果

于 2013-04-01T09:49:30.973 回答
0
SELECT COUNT(*) as total, SUM(visits) as total_visits FROM stories;
于 2013-04-01T09:49:00.630 回答
0
SELECT Story.*, COUNT(*) as total, SUM(Story.visits) as total_visits FROM stories AS Story;

如果您想获得其他字段SUMCOUNT使用.*.

于 2013-04-01T09:52:00.963 回答
-1

是的,试试这个:

$stmt = $db->query('SELECT count(*),sum(visits) FROM stories');
$result = $stmt->fetch_array(MYSQLI_NUM);
$story_count = $result[0];
$total_visits = $result[1];
于 2013-04-01T09:53:32.913 回答