如何使用在SQL中使用左连接选择前1个子查询

时间:2016-09-01 15:26:42

标签: sql sql-server

我试图执行这个查询,但它不work.Kindly帮我这个解决方案我要选择对从子查询相关的职位最高的1图像与左连接

SELECT DISTINCT tblAdvertisement.AdvID, 
                tblAdvertisement.CityName, 
                tblAdvertisement.Model, 
                tblAdvertisement.Year, 
                tblAdvertisement.Mileage, 
                tblAdvertisement.imgPath, 
                tblAdvertisement.Price, 
                tblAdvertisement.VoteScore, 
                tblLike.isLike 
FROM            tblAdvertisement 
LEFT JOIN       tblimg 
                ( 
                       SELECT TOP 1 
                              ImgPath 
                       FROM   tblimg ) AS 
ON              tblAdvertisement.AdvID = tblimg.AdvID 
LEFT JOIN       tblLike 
ON              tblAdvertisement.AdvID = tblLike.AdvID 
AND             tblAdvertisement.UserID = @userID 
ORDER BY        AdvID DESC

1 个答案:

答案 0 :(得分:5)

您需要使用<script src="https://www.gstatic.com/charts/loader.js"></script> <div id="example_scatter_chart"></div>

OUTER APPLY

请注意,如果您需要SELECT DISTINCT A.AdvID, A.CityName, A.Model, A.Year, A.Mileage, I.imgPath, A.Price, A.VoteScore, L.isLike FROM tblAdvertisement A OUTER APPLY ( SELECT TOP 1 ImgPath FROM tblimg WHERE AdvID = A.AdvID ORDER BY SomeColumnToOrderBy) I LEFT JOIN tblLike L ON A.AdvID = L.AdvID AND A.UserID = @userID ORDER BY A.AdvID DESC; 图片,则应该执行TOP 1,否则您将获得一些任意行而不是您想要的那一行。