我编写了以下 SQL,
SELECT COUNT(f.productid) AS count
FROM `product_list` `f`
LEFT JOIN `product_requests` `r`
ON `r`.`product_id` = `f`.`productid`
WHERE `f`.`product_cat` IN( 1, 4 )
AND `f`.`product_subcat` IN( '1', '2', '3', '4',
'5', '6', '7', '9',
'10', '11')
AND `r`.`product_id` IS NULL
我想要做的是获取尚未针对特定产品类别和产品子类别提出产品请求的产品数量。
- product_list 表 - 产品列表
- product_requests 表 - 每个产品的请求列表
查询没有给出输出?超时了。
可能是什么问题?
最佳答案
试试这个:
SELECT COUNT (f.productid) AS COUNT
FROM (SELECT *
FROM `product_list` f where `f`.`product_cat` IN( 1, 4 )
AND `f`.`product_subcat` IN( '1', '2', '3', '4',
'5', '6', '7', '9',
'10', '11') ) `f`
LEFT JOIN `product_requests` `r`
ON `r`.`product_id` = `f`.`productid` AND `r`.`product_id` IS NULL
您的情况:
where
...
`r`.`product_id` IS NULL
需要位于ON子句中,否则它会将您的左连接转换为内连接。了解更多详情请see this link .
此外,为了优化,请尝试在加入之前进行过滤。
关于mysql - 用于获取没有请求的产品数量的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56108724/