你好,我可以在一个查询中合并这两个查询我的第一个查询获取数据库中的文章数量,第二个查询得到所有文章的所有访问量的总和,这是使其成为一个查询的最佳方法
$stmt = $db->query('SELECT * FROM stories');
$story_count = $stmt->rowCount();
$stmt = $db->query("SELECT sum(visits) FROM stories");
$total_visits = $stmt->fetchColumn();
答案 0 :(得分:1)
尝试
$stmt = $db->query('SELECT COUNT(*) as total_cnt,
SUM(visits) as total_visits FROM stories');
然后执行您的查询,您将获得“total_cnt”和“total_visits”的结果
答案 1 :(得分:0)
SELECT COUNT(*) as total, SUM(visits) as total_visits FROM stories;
答案 2 :(得分:0)
SELECT Story.*, COUNT(*) as total, SUM(Story.visits) as total_visits FROM stories AS Story;
如果您希望其他字段与SUM
和COUNT
一起使用.*
。
答案 3 :(得分:-1)
是的,试试这个:
$stmt = $db->query('SELECT count(*),sum(visits) FROM stories');
$result = $stmt->fetch_array(MYSQLI_NUM);
$story_count = $result[0];
$total_visits = $result[1];