我有两张表objectTable
和photo_table
。以下是objectTable
ID TEXT
1 Kaunas
2 Vilnius
3 Palanga
4 Prienai
以及来自photo_table
OBJECT_ID PHOTO_ID NAME
1 7 tets7.jpg
1 8 tets8.jpg
1 9 tets9.jpg
1 10 tets10.jpg
1 11 tets11.jpg
2 3 tets3.jpg
2 2 tets2.jpg
3 1 tets1.jpg
3 5 tets5.jpg
4 6 tets6.jpg
4 7 tets7.jpg
4 8 tets8.jpg
因此,您可以看到一个对象可以有很多图片。我需要得到第一张照片(我的输出应该是)
ID TEXT NAME
1 Kaunas tets7.jpg
2 Vilnius tets3.jpg
3 Palanga tets1.jpg
4 Prienai tets6.jpg
这是我的疑问:
select *
from objectTable
inner join photo_table
on photo_table.OBJECT_ID = (select OBJECT_ID
from photo_table
where photo_table.OBJECT_ID = objectTable.ID
order by photo_table.OBJECT_ID desc
limit 1).
然而,我试图计算近3个小时为什么这个查询不起作用。我错过了什么?我的逻辑是否正确?
答案 0 :(得分:3)
尝试这种方式:
SELECT t1.*, t3.NAME
FROM objectTable AS t1
INNER JOIN (
SELECT OBJECT_ID, MIN(PHOTO_ID) AS PHOTO_ID
FROM photo_table
GROUP BY OBJECT_ID
) t2 ON t1.ID = t2.OBJECT_ID
INNER JOIN photo_table AS t3 ON t3.OBJECT_ID = t2.OBJECT_ID AND
t3.PHOTO_ID = t2.PHOTO_ID
诀窍是使用派生表,每个PHOTO_ID
选择OBJECT_ID
值。此值用于photo_table
的其他联接,以便选择所需的NAME
值。
答案 1 :(得分:0)
对我来说,按照您的代码,我将更改ASC的DESC和订购它的ID列,以获取ID最低的照片
select *
from objectTable
inner join photo_table
on photo_table.OBJECT_ID = (select OBJECT_ID
from photo_table
where photo_table.OBJECT_ID = objectTable.ID
order by photo_table.PHOTO_ID ASC
limit 1).