我不知道这个查询有什么问题:
select * from products , top 1 * from pic
where products.productId = pic.productId
我有产品和Pic表,每个产品都可以有1到n pic,我想返回每个产品和第一张照片
图表的图片可能有助于
答案 0 :(得分:3)
你需要有一种唯一识别每张图片的方法,所以我把那张桌子作为一个ID列......
SELECT
*
FROM
products
LEFT JOIN
pic
ON pic.Id = (SELECT TOP 1 id FROM pic WHERE productID = products.ProductID ORDER BY id DESC)
修改强>
受另一个答案的启发,改为使用APPLY ......
SELECT
*
FROM
products
OUTER APPLY
(SELECT TOP 1 * FROM pic WHERE productID = products.ProductID ORDER BY id DESC) AS pic
答案 1 :(得分:0)
你需要一个子查询
SQL声明
SELECT *
FROM Products prod
LEFT OUTER JOIN Pic p ON p.ProductID = prod.ProductID
LEFT OUTER JOIN (
SELECT PicID = MIN(PicID)
, ProductID
FROM Pic
GROUP BY
ProductID
) pm ON pm.PicID = p.PicID
答案 2 :(得分:0)
还有分段的方法,但请尽量避免在你的TSQL中选择子选择
Select
*
,(select top(1) adress from pic where pic.productid=products.id /* if u wanna you also can order by id */ ) as Id
from products