使用SQL从两个单独的表返回输出

时间:2013-02-25 16:34:28

标签: sql postgresql

我有两张表productsassets。它们由表assets_products加入。

我需要返回一个包含productsassets所有行的表格,同时还会显示assets_products中两者的关​​联行数。

并非所有产品都有资产,反之亦然,我需要以零数显示。

例如:

product   asset    count
 foo        x        1
 bar        x        0
 foo        y        2
 bar        y        1

2 个答案:

答案 0 :(得分:1)

select products.product,
       assets.asset,
       COUNT(assets_products.id) as count
from assets
cross join products
left join assets_products
    on (assets_products.asset_id = assets.id and
        assets_products.product_id = products.id)
group by products.product, assets.asset

答案 1 :(得分:0)

select p.product,a.asset,count(*)
from product p
full outer join product_asset pa 
on pa.product_id=p.product_id
full outer join asset a
on a.asset_id=pa.asset_id
group by p.product_id,a.asset_id