简体   繁体   中英

INNER JOIN with Data Exits Condition

I am writing query to fetch data from two table, Products and ProductsImages. my query is:

    SELECT p.*, pi.*
    FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY ProductId, ProductPrice 
    ORDER BY ProductId) AS row_number FROM Products ) p
    INNER JOIN ( SELECT *, ROW_NUMBER() 
     OVER (PARTITION BY ProductId, ImageId,ImagePath  
    ORDER BY ImageId) AS row_number FROM ProductsImages ) pi 
    ON  p.ProductId = pi.ProductId
    AND p.row_number = pi.row_number
    Where p.ProductId='131';

I have to write a condition for running INNER JOIN that is: Implement INNER JOIN if ProductsImages has images of giving productId else it should run without join . and show just products detail except images. this query is not showing the product detail like name and price if productsImages dont have any image.
Restriction: I have to implement only INNER JOIN. kindly help me out and guide me how can i implement if-exits condition in this case. thanx

In such case why don't you write left join,

Left join keeps all the records from product table even for non matched records with image table

 SELECT p.*, pi.*
    FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY ProductId, ProductPrice 
    ORDER BY ProductId) AS row_number FROM Products ) p
    LEFT OUTER JOIN ( SELECT *, ROW_NUMBER() 
     OVER (PARTITION BY ProductId, ImageId,ImagePath  
    ORDER BY ImageId) AS row_number FROM ProductsImages ) pi 
    ON  p.ProductId = pi.ProductId
    AND p.row_number = pi.row_number
    Where p.ProductId='131';

You can try the inner query way. Example:

SELECT p.*, ( SELECT *, ROW_NUMBER() 
OVER (PARTITION BY ProductId, ImageId,ImagePath  
ORDER BY ImageId) AS row_number FROM ProductsImages pi WHERE p.ProductId = pi.ProductId AND p.row_number = pi.row_number )
FROM ( SELECT *, ROW_NUMBER() OVER (PARTITION BY ProductId, ProductPrice 
ORDER BY ProductId) AS row_number FROM Products ) p
Where p.ProductId='131';

There is no join in this. :(

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM