我可以显示产品列表,但我想从view_product表中不显示产品的观看次数
product_tbl表
----------------------------------
pro_id | product | description
----------------------------------
1 | prodcut1 | description
----------------------------------
2 | prodcut2 | description
----------------------------------
3 | prodcut3 | description
----------------------------------
view_product表
------------------------------------------
view_id | username | product | view_time
------------------------------------------
1 | usename1 | prodcut1 | 2019-10-31 11:45:00
------------------------------------------
2 | usename2 | prodcut1 |2019-10-31 11:46:00
------------------------------------------
3 | usename2 | prodcut1 |2019-10-31 11:45:00
------------------------------------------
4 | usename1 | prodcut1 |2019-10-31 11:46:00
------------------------------------------
$stmt = $conn->prepare("Select pro_id,product, description,qty from product_tbl");
$stmt->execute();
$row = $stmt-> fetchAll(PDO::FETCH_ASSOC);
$user_arr=array('data'=>$row);
echo json_encode($user_arr);
基于product_id,我想从view_product表和空值行中查看每个产品的计数(如果未查看产品),如何在PDO json编码中使用以下查询。
select count(id) as count1 from view_product where user_id=".$row['pro_id'].";
预期输出如下
------------------------------------------------
pro_id | product | description | view count
------------------------------------------------
1 | prodcut1 | description | 2
------------------------------------------------
2 | prodcut2 | description | 2
------------------------------------------------
3 | prodcut3 | description | NULL
------------------------------------------------
答案 0 :(得分:0)
避免使用n + 1个查询,而应将join语句与count()
函数结合使用,并在最后将它们按列分组。
SELECT
p.prod_id,
p.product,
p.description,
COUNT(v.view_id) AS view_count
FROM product_tbl AS p
LEFT JOIN view_product AS v ON p.product = v.product
GROUP BY v.product