我有三张表,这样连接
[播放列表] .DBI_ID = 1:1 = [SUB_FILES] .SBF_PLY_ID = *:1 = [STL] .DBI_ID
从这个数据库中,我可以获取一些数据:
SELECT
PLAYLIST.dbi_id as PLY_ID,
SUB_FILES.dbi_id as SBF_ID,
SUB_FILES.dbi_created_time as SBF_CREATED,
STL.dbi_id as STL_ID
FROM PLAYLIST, SUB_FILES, STL
WHERE (PLAYLIST.ply_automation_id = 'F0117705'
OR PLAYLIST.ply_automation_id = 'F0117707')
AND (SUB_FILES.sbf_ply_id = PLAYLIST.dbi_id)
AND (SUB_FILES.sbf_stl_id = STL.dbi_id)
PLAYLIST.ply_automation_id = ...
条件仅用于测试。最后,我将在整个PLAYLIST表上运行查询。
我无法弄清楚如何只为每个不同的STL_ID值获取具有最小SBF_CREATED日期的记录。
换句话说,我只想获取PLY_ID的14.604(其中两个记录的最小SBF_CREATED,STL_ID = 5.596)和14.747(具有STL_ID的所有四个记录中SBF_CREATED最小的数据)的数据= 5.642)。
有问题的数据库是Firebird 2.1,但如果可能的话,我对一般的SQL答案感兴趣。
答案 0 :(得分:3)
根据你的描述我会假设你真正想要的结果是:
PLY_ID SBF_ID SBF_CREATED STL_ID
14.604 16044 2008-11-28 15:46:00.000 5.596
14.747 16.210 2008-12-11 11:30:00.000 5.642
因为那些是SBF_CREATED
最低的那些。
您可以做的是找到您加入的派生表中每个sbf_stl_id
的最低日期:
SELECT
PLAYLIST.dbi_id as PLY_ID,
SUB_FILES.dbi_id as SBF_ID,
SUB_FILES.dbi_created_time as SBF_CREATED,
STL.dbi_id as STL_ID
FROM PLAYLIST
JOIN SUB_FILES ON SUB_FILES.sbf_ply_id = PLAYLIST.dbi_id
JOIN STL ON SUB_FILES.sbf_stl_id = STL.dbi_id
JOIN
(
SELECT sbf_stl_id, MIN(dbi_created_time) AS min_dbi_created_time
FROM SUB_FILES
GROUP BY sbf_stl_id
) AS sub ON sub.sbf_stl_id = stl.dbi_id
AND sub.min_dbi_created_time = SUB_FILES.dbi_created_time
WHERE (PLAYLIST.ply_automation_id = 'F0117705' OR PLAYLIST.ply_automation_id = 'F0117707')
当我使用SQL Server进行测试时,这会产生预期的结果,但由于它不使用任何特殊的产品特定功能,而只使用标准SQL,因此它应该适用于任何符合标准的数据库。