获取两个连接表中相关记录的计数

时间:2014-06-15 09:31:30

标签: sql join

首先,我为我的英语道歉。我希望得到有关出价和购买次数的拍卖。它应该是这样的:

id | name | bids | buys
-----------------------
1  | Foo  |  4   |  1 
2  | Bar  |  0   |  0

我有以下表格:

拍卖

id | name
---------
1  | Foo
2  | Bar

auction_bid

id | auction_id
---------------
 1 |    1 
 2 |    1
 3 |    1
 4 |    1

auction_buy

id | auction_id
---------------
 1 |    1 

我可以在两个查询中获得数字:

SELECT *, COUNT(abid.id) AS `bids` FROM `auction` `t` LEFT JOIN auction_bid abid ON (t.id = abid.auction) GROUP BY t.id 

SELECT *, COUNT(abuy.id) AS `buys` FROM `auction` `t` LEFT JOIN auction_buy abuy ON (t.id = abuy.auction) GROUP BY t.id 

但是当我把它合二为一时:

SELECT *, COUNT(abid.id) AS `bids`, COUNT(abuy.id) AS `buys` FROM `auction` `t` LEFT JOIN auction_bid abid ON (t.id = abid.auction) LEFT JOIN auction_buy abuy ON (t.id = abuy.auction) GROUP BY t.id 

它返回了错误的金额(出价与买入一样多)。

如何修复此问题并在一个查询中获取计数?

2 个答案:

答案 0 :(得分:3)

您需要计算DISTINCT abuy和abid ID以消除重复项;

SELECT t.id, t.name, 
       COUNT(DISTINCT abid.id) `bids`,
       COUNT(DISTINCT abuy.id) `buys`
FROM `auction` `t` 
LEFT JOIN auction_bid abid ON t.id = abid.auction_id
LEFT JOIN auction_buy abuy ON t.id = abuy.auction_id
GROUP BY t.id, t.name;

An SQLfiddle to test with

答案 1 :(得分:2)

试试这个:

SELECT t.*,COUNT(abid.id) as bids,buys
FROM auction t LEFT JOIN 
      auction_bid abid ON t.id = abid.auction_id LEFT JOIN
(SELECT t.id, Count(abuy.id) as buys
 FROM auction t LEFT JOIN 
      auction_buy abuy ON t.id = abuy.auction_id 
 GROUP BY t.id) Temp ON t.id=Temp.id
GROUP BY t.id

结果:

ID  NAME    BIDS    BUYS
1   Foo     2       0
2   Bar     1       1

结果为SQL Fiddle