简体   繁体   English

根据不同表中的ID计算所有行

[英]Count all row based on id from a different table

I want to count the photo based on product id . 我想根据product idphoto进行计数。 I think there is something to do in loop counting. 我认为循环计数中有一些事情要做。 So I coded as following but I got 所以我编码如下

Fatal error: Call to a member function fetch_assoc() on a non-object 致命错误:在非对象上调用成员函数fetch_assoc()

<?
include_once($_SERVER['DOCUMENT_ROOT']."/cgi-bin/connect.php");

$stmt=$mysqli->prepare("select * from products_db order by prd_id");
$stmt->execute();
$result=$stmt->get_result();
$data=array();
while($row=$result->fetch_assoc()){
    //count no. of img in loop
    $stmt=$mysqli->prepare("select pic_id from photo_db where pic_sid=?");
    $stmt->bind_param('s',$row['prd_sid']);
    $result=$stmt->get_result();
    $nPic=$result->num_rows;

    $data[]=array($row['prd_code'],$row['prd_en'],$row['cat_id'],
number_format($row['prd_cost']),$row['prd_stts'],$nPic,$row['prd_rcm']);
}
echo json_encode(array('data' => $data));
?>

Then I do : 然后我做:

$stmt=$mysqli->prepare("select *,count(pic.pic_id) as npic 
from products_db prd 
inner join 
photo_db pic 
on prd.prd_sid=pic.pic_sid 
order by prd.prd_id");

It's working BUT SOME PRODUCTS WAS UNSHOWN BECAUSE NO RELATED pic_sid FROM photo_db 它正在工作, 但是由于没有与pic_sid相关的pic_sid photo_db

I want all product display the photo count even there's none of them existed in DB. 我希望所有产品都显示照片计数,即使数据库中不存在它们也是如此。

试试这个查询,我希望它能起作用。

select count(pi.pic_id),pr.* from photo_db pi where pi.pic_sid in (select pr.prd_sid from products_db pr ) group by pi.pic_id

Thank to the advice from @Sayed Mohd Ali . 感谢@Sayed Mohd Ali的建议。 I come up with the solutions. 我想出了解决方案。

select *,
(select count(pic_id) as npic from photo_db where pic.pic_sid=prd.prd_sid) as npic
from products_db prd
left join photo_db pic on pic.pic_sid=prd.prd_sid
group by prd.prd_sid

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM