This problem is extremely difficult to explain and I did not even know how to title it correctly so I do apologise about that in advance.
I have a view of products which is as follows:
Product
ProductId
ProductName
In my database, I have a ratecard table and a ratecard product table. A ratecard may be titled "Tier 1 Customers" and the corresponding RatecardProduct records would be prices for products for that particular ratecard. It may only contain prices for a few products and not all of them.
Ratecard
RatecardId
RatecardName
RatecardProduct
RatecardProductId
RatecardId
ProductId UnitPrice
The problem is that I need to create a view which displays all products for all ratecards. If the ratecard / product combination does not have a corresponding unit price in my ratecardproduct table, it should show NULL or 0.
Imagine I have 10 products and 4 ratecards; the view would contain 40 records, even if the RatecardProduct table was completely empty
The reason I need to do this is because I am populating a gridview on viewing a ratecard and I do not want to have to do a round trip for each row to ascertain if there is a corresponding price.
Thank you so much in advance.
Generate all the rows. Then use left join
to bring in the data:
select p.*, r.*, coalesce(rp.unitprice, 0) as unitprice
from products p cross join
ratecards r left join
ratecardproduct rp
on rp.productid = p.productid and rp.ratecardid = r.ratecardid;
Or don't use coalesce()
if you want NULL
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.