PHP MySQL计数来自INNER JOIN - GROUP BY的行

时间:2016-11-20 01:45:00

标签: php mysql

我在这里尝试做的是,我想要输出id的{​​{1}}和user_id列的计数,排名为{{1}的用户}。 假设items中有8行,1 400 ,这8行,其中2行有items 4 ,现有左侧的base_item 6
输出应为: user_iduser_id

$countItems = 8

我尝试了多种方法,但即使结果应为$countUsers = 2$stmt = $conn->pdo->prepare(" SELECT COUNT(*),`user_id` FROM `items` INNER JOIN `users` ON `users`.`id` = `items`.`user_id` WHERE `base_item` = :i AND `rank` = 1 GROUP BY `user_id`,`items`.`id` "); $data = array(':i' => '400'); // item_id in `values` table $stmt->execute($data); if($inv = $stmt->fetch($db->FETCH_ASSOC)) { $countItems = $inv['id']; $countUsers = $inv['user_id']; } ,我仍然会继续输出22

8的表格信息: enter image description here

2的表格信息: enter image description here

3 个答案:

答案 0 :(得分:1)

首先,你永远不想fetchAll()并丢弃数据只是为了计算行数。还有更好的方法。

SELECT COUNT(*) FROM `items` WHERE `base_item` = :item AND `user_id` = :uid

其次,您应该尽可能避免嵌套循环,因为嵌套循环不能很好地扩展。解决方案是使用连接或子查询。您尚未发布表格结构,因此此查询未经过测试。

 SELECT COUNT(*), user_id FROM `items` INNER JOIN users 
 ON users.id = items.user_id
 WHERE `base_item` = :item and rank =1 GROUP BY user_id 

一个查询而不是两个,更少的代码行数。

答案 1 :(得分:0)

问题是你正在用foreach循环替换$smst

使用其他变量名称,例如:

$stmt->execute();
foreach($stmt as $user) {
   $stmt2 = $conn->pdo->prepare("SELECT `id`,`user_id` FROM `items` WHERE `base_item` = :item AND `user_id` = :uid");
   $stmt2->bindParam(':item', $cmsval['item_id'], $db->PARAM_INT);
   $stmt2->bindParam(':uid', $user['id'], $db->PARAM_INT);

答案 2 :(得分:0)

好吧,我实际需要做的就是删除GROUP BY并添加COUNT DISTINCT,如下所示:

$stmt = $conn->pdo->prepare("
   SELECT COUNT(DISTINCT `user_id`) as `uid`, 
          COUNT(`items`.`id`) as `id` 
   FROM `items` 
   INNER JOIN `users`
   ON `users`.`id` = `items`.`user_id`
   WHERE `base_item` = :i AND `rank` = 1
");
$stmt->bindParam(':i', $cmsval['item_id'], $db->PARAM_INT);
$stmt->execute();
if($inv = $stmt->fetch($db->FETCH_ASSOC)) {
    $countItems = $inv['id'];
    $countUsers = $inv['uid'];
}