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

时间:2012-08-29 20:00:10

标签: php mysql join

我有一个表shop_inventory和另一个shops。我想计算来自DISTINCT zbid的{​​{1}}的数量以及shop_inventoryshops的行数。我试过这样:

cid=1 AND zbid!=0

然而,这返回了100家商店而不是2家,这是正确的答案。我想我不明白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 如何正常工作。有人可以为此查询提供修复程序吗?

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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

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