1

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

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,我只想返回具有最大或最小 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

我想我需要一些最大或最小的东西,但是我无法将它与另一个外部连接(不需要最大或最小)结合起来。任何帮助表示赞赏,如果您需要更多信息,请告诉我。

4

3 回答 3

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

我不想取最小光泽名称,因为我知道您的最小值应该基于光泽顺序。

于 2013-11-15T05:29:05.297 回答
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
于 2013-11-15T05:26:01.897 回答
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
于 2013-11-15T05:28:19.307 回答