我有两个表:tblBusinesses,tblBusinessImages在tblBusinesses.fldID = tblBusinessImages.fldBusinessID上匹配如下:
tblBusinesses
=============
fldID | fldName | fldTitle | fldBody
-------------------------------------
1 | b1 | title1 | body1
2 | b2 | title2 | body2
3 | b3 | title3 | body3
4 | b4 | title4 | body4
tblBusinessImages
=============
fldID | fldFileName | fldTitle | fldBusinessID | fldOrder
-----------------------------------------------------------
1 | img1.jpg | img1title | 1 | 3
2 | img2.jpg | img2title | 1 | 1
3 | img3.jpg | img3title | 1 | 2
我想编写一个查询来获取tblBusinesses中的每个业务,tblBusinessImages中的图像使用最小的fldOrder。换句话说,在我上面写的示例中,我想从tblBusinessImages获取业务b1,title1,body1和img2.jpg(因为它在tblBusinessImages中具有最小的fldOrder)。
任何帮助将不胜感激!
答案 0 :(得分:0)
如果fldOrder
alwyas从每个fldBusinessID
开始,则查询变为
SELECT b.fldName, b.fldTitle, b.fldBody, i.fldFileName
FROM
tblBusinesses b
LEFT JOIN tblBusinessImages i
ON (b.fldID = i.fldBusinessID AND i.fldOrder = 1)
如果没有,则必须使用子查询。
SELECT b.fldName, b.fldTitle, b.fldBody, firstImage.fldFileName
FROM
tblBusinesses b
LEFT JOIN (
SELECT i.fldBusinessID, i.fldFileName
FROM
tblBusinessImages i
WHERE
i.fldOrder = (SELECT MIN(x.fldOrder)
FROM tblBusinessImages x
WHERE x.fldBusinessID = i.fldBusinessID)
) firstImage
ON b.fldID = firstImage.fldBusinessID
请注意,左连接会使查询返回完全没有图像的商家。
如果您只需要包含最小订单ID可以包含任何值的图像的条目:
SELECT b.fldName, b.fldTitle, b.fldBody, i.fldFileName
FROM
tblBusinesses b
INNER JOIN tblBusinessImages i
ON b.fldID = i.fldBusinessID
WHERE
i.fldOrder = (SELECT MIN(x.fldOrder)
FROM tblBusinessImages x
WHERE x.fldBusinessID = i.fldBusinessID)
答案 1 :(得分:0)
您是否只想获得最小fldOrder的ONE条目? 没有测试这个查询:
SELECT b.fldName,b.fldTitle,b.fldBody,bi.fldFileName,bi.fldOrder
FROM tblBuisnesses b
INNER JOIN tblBuisnessImages bi ON bi.fldBusinessID=b.fldID ORDER BY b.fldOrder DESC LIMIT 1;