将 MySQL 查询转换为 SQL Server (MSSQL / SQLSRV)(WiTH DISTINCT)
我需要做什么才能将此查询转换为在 SQL Server 中工作?
SELECT
DISTINCT(map_objetivos.OBJ_RowID) AS test,
map_objetivos.OBJ_Objetivo
FROM
map_admin_caminho_critico_indicadores
INNER JOIN
map_admin_caminho_critico ON CCR_RowID = CCI_CaminhoDR
INNER JOIN
map_indicadores ON IND_RowID = CCI_IndicadorDR
INNER JOIN
map_objetivos ON OBJ_RowID = IND_ObjetivoDR
GROUP BY
map_objetivos.OBJ_RowID
What do I need to do to convert this query to work within in SQL Server?
SELECT
DISTINCT(map_objetivos.OBJ_RowID) AS test,
map_objetivos.OBJ_Objetivo
FROM
map_admin_caminho_critico_indicadores
INNER JOIN
map_admin_caminho_critico ON CCR_RowID = CCI_CaminhoDR
INNER JOIN
map_indicadores ON IND_RowID = CCI_IndicadorDR
INNER JOIN
map_objetivos ON OBJ_RowID = IND_ObjetivoDR
GROUP BY
map_objetivos.OBJ_RowID
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
SQL Server 与 MySQL 不同,不允许在选择列表中出现未聚合或分组的字段。另外,您的
DISTINCT
是多余的。试试这个:SQL Server, unlike MySQL, won't allow unaggregated or grouped fields in the select list. Also, your
DISTINCT
is redundant. Try this:该查询比在 group by 子句中包含额外字段的查询运行得更快。
如果您希望查询快速运行,则只需将这些字段放入唯一定义所选字段的组中即可。
使用 MIN() 或 MAX() 聚合来让 SQL 服务器停止抱怨。
由于其他选定字段在功能上取决于 group by 子句,因此结果集中的每一行只会有一个值,并且 MAX() 函数不会减慢您的速度。
超长的 group by 子句会减慢查询速度。
请记住,仅当其他字段在功能上依赖于 group by 子句时才使用此技巧
关于 Distinct
此代码:
与此代码相同
您不能在选择中的单个字段上使用
DISTINCT
。如果您想这样做,请在子选择中使用带有单个字段的
GROUP BY
。This query will run faster than a query with extra fields in the group by clause.
If you want your queries to run fast, you need to only put those fields in the group by that uniquely define the selected fields.
Use a MIN() or MAX() aggregate to get SQL-server to stop complaining.
Because the other selected fields are functionally depended on the group by clause, there will only ever be one value per row in the resultset and the MAX() function will not slow you down.
The extra long group by clause will slow your query down.
Remember to only use this trick if the other fields are functionally dependent on the group by clause
About Distinct
This code:
Is the same as this code
You cannot use
DISTINCT
on a single field in the select.If you want to do that use a
GROUP BY
with a single field in a subselect.您正在对一个字段进行分组,但第二个字段未用于聚合。尝试以下操作。
编辑:正如 JNK 提到的 - 在这种情况下不同是多余的。
You are grouping on one field but the second field is notused in an aggregate. Try the following.
Edit: As JNK mentioned - distinct in this case is redundant.