-2

我有两张桌子productsassets. 它们由一张桌子连接起来assets_products

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

并非所有产品都有资产,反之亦然,我需要用零计数来展示这一点。

例如:

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

2 回答 2

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
于 2013-02-25T17:11:44.390 回答
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
于 2013-02-25T17:08:41.443 回答