我正在编写查询以从两个表Products,ProductsImages中获取数据。 我的疑问是:
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';
我必须编写一个运行INNER JOIN的条件:如果ProductsImages具有提供productId 的图像,则实现INNER JOIN,否则它应该在没有连接的情况下运行。并且仅显示除图像之外的产品详细信息。如果productsImages没有任何图像,此查询不会显示产品详细信息,如名称和价格。
限制:我必须只实施INNER JOIN。
请帮助我并指导我如何在这种情况下实现if-exits条件。感谢名单
答案 0 :(得分:1)
在这种情况下,你为什么不写left join,
左连接保留产品表中的所有记录,即使对于具有图像表的非匹配记录
也是如此 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';
答案 1 :(得分:1)
您可以尝试内部查询方式。例如:
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';
此处没有加入。 :(