在firebirdsql中连接三个表

时间:2014-11-27 10:26:00

标签: sql join firebird

我有这个问题: 我想加入三个表来获取一些值,例如:

Sellers
IDSELLERS
NAMESELLER

STOCK
IDSTOCK
QTYSTOCK
COST
FKSELLER

SELL
IDSELL
QTYSELL
PRICE
FKSELLER

我想了解每个卖家的STOCKSELL表的总数

您已尝试使用以下查询,但它将每次卖出的值加倍:

select
SELLERS.NAMESELLER,
SUM(STOCK.QTY*STOCK.COST)AS STOCKS,
SUM(SELL.QTY*SELL.PRICE) AS SELLS
FROM
SELLERS
LEFT JOIN STOCK ON STOCK.FKSELLER=SELLERS.IDSELLER
LEFT JOIN SELL ON SELL.FKSELLER=SELLERS.IDSELLERS
GROUP BY
SELLERS.NAMESELLER

使用的firebirdsql版本是2.1

提前致谢。

1 个答案:

答案 0 :(得分:2)

问题在于,如果您在 sell 中有2个,在 stock 中有2个。第一个连接将生成两个记录,第二个连接将创建2 * 2个记录。相反,您应该将数据合并并连接一次,或使用选择表达式来生成总和。

使用选择表达式:

select
  SELLERS.NAMESELLER,
  (select sum(STOCK.QTY * STOCK.COST) 
     from STOCK where STOCK.FKSELLER=SELLERS.IDSELLER) AS STOCKS,
  (select sum(SELL.QTY * SELL.PRICE) 
     from SELL where SELL.FKSELLER=SELLERS.IDSELLERS) AS SELLS
from SELLERS

使用联盟:

select 
  SELLERS.NAMESELLER,
  sum(stocksell.STOCKQTY * stocksell.STOCKCOST) AS STOCKS,
  sum(stocksell.SELLQTY * stocksell.SELLPRICE) AS SELLS
from SELLERS
left join (
  select FKSELLER, QTY AS STOCKQTY, COST AS STOCKCOST, 
         0 AS SELLQTY, 0 AS SELLPRICE
  from STOCK
  union all
  select FKSELLER, 0 AS STOCKQTY, 0 AS STOCKCOST, 
         QTY AS SELLQTY, PRICE AS SELLPRICE
  from SELL
) stocksell
  ON stocksell.FKSELLER=SELLERS.IDSELLER
group by SELLERS.NAMESELLER