0

我有一张桌子shop_inventory和另一张桌子shops。我想计算DISTINCT zbidfrom的数量和whereshop_inventory的行数。我试过这样:shopscid=1 AND zbid!=0

SELECT COUNT(a.cid) shops,COUNT(DISTINCT b.zbid) buyers 
FROM shops a 
JOIN shop_inventory b ON b.cid=a.cid 
WHERE a.zbid!=0 AND a.cid=1

但是,这返回了 100 个商店而不是 2 个,这是正确的答案。我想我不明白如何JOIN正确工作。有人可以为这个查询提供修复吗?

4

2 回答 2

1

许多相关行上的JOIN商店数量都在减少。

试试这个解决方案:

SELECT COUNT(DISTINCT a.cid, a.zbid) shops, 
       COUNT(DISTINCT b.zbid) buyers
FROM   shops a
JOIN   shop_inventory b ON a.cid = b.cid
WHERE  a.cid = 1 AND a.zbid <> 0
于 2012-08-29T20:03:01.310 回答
0

如果这让你得到你想要的商店数量:

SELECT COUNT(1) AS shops
  FROM shops a
 WHERE a.zbid != 0
   AND a.cid = 1

然后,包含另一个表的计数的一种方法是使用相关子查询。(这种方法存在一些性能问题,如果外部查询返回有限数量的行,这种方法效果很好。)

SELECT COUNT(1) AS shops
     , ( SELECT COUNT(DISTINCT b.zbid)
           FROM shop_inventory b
          WHERE b.cid = a.cid
       ) AS buyers
  FROM shops a
 WHERE a.zbid != 0
   AND a.cid = 1

另一种方法是使用子查询的连接(内联视图)......

SELECT COUNT(1) AS shops
     , c.buyers AS buyers
  FROM shops a
  JOIN ( SELECT b.cid, COUNT(DISTINCT b.zbid) AS buyers
           FROM shop_inventory b
          WHERE b.cid = 1
          GROUP BY b.cid
       ) c
 WHERE a.zbid != 0
   AND a.cid = 1
   AND a.cid = c.cid

如果那些没有返回您正在寻找的结果集,那么我可能误解了规范。

于 2012-08-29T20:14:33.197 回答