SQL计数达不到我想要的结果



我有两个不同的表Products和ProductImages:

SELECT COUNT(p.productid) AS product_count, COUNT(pi.imageid) AS image_count  
FROM [Products] p, [ProductImages] pi  
WHERE p.productid=126 AND pi.productid=126;  

上面的查询给了我两个计数在每个计数中的多重应用。请指导我哪里错了,我可以用单选查询来完成吗

您可以在两行中获得

SELECT COUNT(p.productid) As Count
FROM [Products] p
WHERE p.productid=126
UNION All
SELECT COUNT(pi.imageid) As Count
FROM  [ProductImages] pi 
WHERE pi.productid=126;

或者您可以在没有UNION ALL的情况下执行此操作

SELECT 
(SELECT COUNT(p.productid) As Count 
From [Products] p WHERE p.productid=126) ) as t1,
(SELECT COUNT(pi.imageid) As Count 
FROM  [ProductImages] pi WHERE pi.productid=126) as t2

通过子查询尝试此操作

SELECT COUNT(p.productid) AS product_count,(Select COUNT(pi.imageid) AS image_count  [ProductImages] pi  Where pi.productid=126; ) FROM [Products] p  WHERE p.productid=126 
SELECT  COUNT(DISTINCT p.productid) AS product_count ,
        COUNT(DISTINCT pi.imageid) AS image_count
FROM    [Products] p ,
        [ProductImages] pi
WHERE   p.productid = 126
        AND pi.productid = 126 ;  

相关内容

最新更新