我有两张桌子,我必须加入。表结构是
tblproducts - > id(int,pk),name(varchar)
tblphotos ---> id(int,pk),productid(int,fk),photo(varchar),display_order(int)
每种产品可以有多张照片,我需要获得一张最低display_order的照片。
我需要,tblproducts.id,tblproducts.name,tblphotos.photo(带最少display_order的照片)我还需要按升序将整个列表作为tblproducts.id。
答案 0 :(得分:1)
Select tblproducts.id, tblproducts.name, (Select Top 1 tblphotos.photo FROM tblphotos, tblproducts Where tblphotos.productid = tblproducts.id Order By display_order)
From tblproducts, tblphotos
Where tblproducts.id = tblphotos.productid
Order by tblproducts.id
编辑:Oppss!我没有看到mysql标签。顺便说一句,这是针对MSSQL的。
是的,此查询看起来像重复。我应该删除Where
条款。
Select tblproducts.id, tblproducts.name, (Select Top 1 tblphotos.photo FROM tblphotos, tblproducts Where tblphotos.productid = tblproducts.id Order By display_order)
From tblproducts
Order by tblproducts.id
答案 1 :(得分:0)
我没有测试过以下查询,但它应该可以运行,试一试:
SELECT
p.id, p.name, f.photo
FROM
tblproducts p,
(
SELECT productid, MIN(display_order) AS min_display_order
FROM tblphoto
GROUP BY productid
) AS t,
tblphoto f
WHERE
p.id = t.productid AND
t.productid = f.productid AND
t.min_display_order = f.display_order
ORDER BY p.id