我有兩個表products
和assets
。他們加入了表assets_products
。用SQL返回兩個單獨的表的輸出
我需要返回一個表,其中包含products
和assets
中的所有行,同時還顯示assets_products
中兩個關聯行的數量。
並非所有產品都有資產,反之亦然,我需要用零計數來顯示。
例如:
product asset count
foo x 1
bar x 0
foo y 2
bar y 1
我有兩個表products
和assets
。他們加入了表assets_products
。用SQL返回兩個單獨的表的輸出
我需要返回一個表,其中包含products
和assets
中的所有行,同時還顯示assets_products
中兩個關聯行的數量。
並非所有產品都有資產,反之亦然,我需要用零計數來顯示。
例如:
product asset count
foo x 1
bar x 0
foo y 2
bar y 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
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
這不會返回任何缺失的'products'或'assets' – 2013-02-25 17:09:38
@rs。 :現在它應該工作。 – ankurtr 2013-02-25 17:15:22
你能可能增加,你希望看到的結果是什麼,你有什麼例子? – 2013-02-25 16:43:41
嘗試使用'Full Outer Join'來獲取行,然後執行'count' – 2013-02-25 17:08:34