我有两张表products
和assets
。它们由表assets_products
加入。
我需要返回一个包含products
和assets
所有行的表格,同时还会显示assets_products
中两者的关联行数。
并非所有产品都有资产,反之亦然,我需要以零数显示。
例如:
product asset count
foo x 1
bar x 0
foo y 2
bar y 1
答案 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