如何在Postgres sql中联接3个表

时间:2018-12-10 14:38:16

标签: sql postgresql join

我有三个桌子

物料主数据:存储物料主数据详细信息

id integer NOT NULL DEFAULT, primary key
name character varying(255),
description character(255),
price double precision,
tax double precision,
readytosales character(1) DEFAULT 'N'::bpchar,
itemgroupid integer,
uom character varying(30),
quantity double precision DEFAULT 0,

购买:存储购买详细信息

purchaseid integer NOT NULL DEFAULT,
quantity double precision DEFAULT 0,
purchasemasterid integer NOT NULL,
itemid integer NOT NULL,
itemprice double precision DEFAULT 0.00,

销售:商店销售明细

salesid integer NOT NULL DEFAULT,
quantity double precision DEFAULT 0,
salesmasterid integer NOT NULL,
itemid integer,
itemprice double 

用于获取库存摘要的公式为

itemmaster.quantity + purchase.quantity -sales.quantity 

我使用以下查询获取详细信息,但无法获取结果

select im.id as itemid, 
       name as itemname,
       im.quantity as oepningquantity, 
       im.price as openingprice,
       (im.quantity * im.price) as openingbalance,
       p.quantity as purchasequantity, p.itemprice as purchaseprice,
       (p.quantity * p.itemprice)as totalpurchaseprice, 
       s.quantity as salesquanity, s.itemprice as saleprice,
       (s.quantity *s.itemprice)as totalsalesprice
from item_master as im 
  full outer join purchase as p on im.id=p.itemid 
  full outer join sales as s on im.id=s.itemid 

3 个答案:

答案 0 :(得分:1)

例如,我们有3个表。 表格1。 表_2。 table_3。

和table_2和table_3由table_1的前键引用。 因此,如果我们将这三个表连接在一起,查询将如下所示。

Select {table 1 Cols} {table 2 Cols} {table 3 Cols}
from table_1
join table_1.table_2ID = table_2.Id on (Specify Condition here)
join table_1.table_3ID = table_3.Id on (Specify Condition here)

答案 1 :(得分:1)

您的查询有一个小问题。 正确的查询是:

Number

_____ from item_master as im ______ -------此陈述有误。

String

答案 2 :(得分:0)

这将起作用:

       select 
       im.id as itemid, 
       name as itemname,
       im.quantity as oepningquantity, 
       im.price as openingprice,
       (im.quantity * im.price) as openingbalance,
       p.quantity as purchasequantity,
       p.itemprice as purchaseprice,
       (p.quantity * p.itemprice)as totalpurchaseprice, 
       s.quantity as salesquanity, 
       s.itemprice as saleprice,
       (s.quantity *s.itemprice)as totalsalesprice
       from 
       Item master im,
       purchase p,
       sales s 
       where
       im.id=p.itemid and
       im.id=s.itemid;