多个外部联接返回最高结果

时间:2013-11-15 05:17:46

标签: sql sql-server outer-join

我有一个带有几个左外连接的查询,为简单起见,我将只包括两个。它看起来像这样:

SELECT Object.ID, Gloss.name, Gloss.order, Title.name from Object
LEFT OUTER JOIN Gloss on Gloss.object_id = Object.ID
LEFT OUTER JOIN Title on Title.object_id = Object.ID

但是,有些项目有多个Gloss,我想只返回一行有max或min Gloss.order。我查询的示例输出如下所示:

|Object.ID | Gloss.name | Gloss.order | Title.name
|4.00      | glossvalue1| 1           | TitleValue
|4.00      | glossvalue2| 2           | TitleValue
|3.00      | gloss3-1   | 11          | OtherTitle
|3.00      | gloss3-2   | 13          | OtherTitle
|3.00      | gloss3-3   | 15          | OtherTitle

理想情况下,我想返回这样的内容:

|Object.ID | Gloss.name | Gloss.order | Title.name
|4.00      | glossvalue1| 1           | TitleValue
|3.00      | gloss3-1   | 11          | OtherTitle

我认为我需要一些最大或最小的东西,但我很难将它与其他外连接(不需要max或min)相结合。 如果您需要更多信息,请与我们联系。

3 个答案:

答案 0 :(得分:1)

这应该做的工作:

SELECT Object.ID, (SELECT name FROM Gloss G WHERE G.object_id = X.object_id AND G.order = X.ord) AS [GlossName],
    X.order, Title.name 
FROM Object
LEFT OUTER JOIN
    (SELECT object_id, MIN(order) ord FROM Gloss GROUP BY object_id) X
ON X.object_id = Object.ID
LEFT OUTER JOIN Title on Title.object_id = Object.ID

我不想拿最小光泽名称,因为我知道你的min应该基于光泽度顺序。

答案 1 :(得分:0)

SELECT Object.ID, min(Gloss.name), min(Gloss.order), Title.name from Object
LEFT OUTER JOIN Gloss on Gloss.object_id = Object.ID
LEFT OUTER JOIN Title on Title.object_id = Object.ID
GROUP BY Object.ID,Title.name

答案 2 :(得分:0)

select object.ID, Gloss.name, min(Gloss.order) as order, Title.name
from object
left outer join Gloss on Gloss.object_id = object.ID
left outer join Title on Title.object_id = object.ID
group by object.ID, Gloss.name, Title.name