简体   繁体   English

形成查询以返回有关两个不同表的信息

[英]Form a query to return information on two different tables

I have one table shop_inventory and another shops . 我有一个桌子shop_inventory和另一个shops I want to count the number of DISTINCT zbid from shop_inventory AND the number of rows in shops where cid=1 AND zbid!=0 . 我想计算来自shop_inventoryDISTINCT zbid数量和cid=1 AND zbid!=0 shops中的行数。 I tried it like so: 我这样尝试:

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

However, this returned 100 shops instead of 2, which is the correct answer. 但是,这返回了100家商店,而不是2家,这是正确的答案。 I guess I'm not understanding how JOIN works correctly. 我想我不了解JOIN如何正常工作。 Can someone offer a fix for this query? 有人可以提供此查询的修复程序吗?

The JOIN on many related rows was throwing off your count of shops. 许多相关行上的JOIN使您的商店数量减少了。

Try this solution: 试试这个解决方案:

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

If this gets you the count of shops you want: 如果这样可以让您获得想要的商店数量:

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

Then one way to include a count from another table is to use a correlated subquery. 然后,包括来自另一个表的计数的一种方法是使用相关子查询。 (There are some performance issues with this approach, this works well if the outer query returns a limited number of rows.) (此方法存在一些性能问题,如果外部查询返回的行数有限,则此方法效果很好。)

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

Another approach is to use a join of the subqueries (inline views)... 另一种方法是使用子查询的联接(内联视图)...

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

If those don't return the result set you are looking for, then I have probably misunderstood the specification. 如果那些没有返回您要查找的结果集,那么我可能误解了规范。

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

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