mysql - 编写与 MySQL 查询等效的 MSSQL (2019) 查询
问题描述
我在我的项目中编写了以下 MySQL 查询,以选择所有具有匹配 test_change 表记录的测试表记录(以第一个为准)用于数据显示目的。
我需要 MSSQL 等效查询,但由于我对它的了解有限,无法形成查询。我尝试了网站http://www.sqllines.com/online但我没有帮助我。
这是 MySQL 查询:
SELECT
tests.*,
cases.title,
users.name,
statuses.label as status_label,
statuses.color_dark,
tc.id as change_id,
tc.created_on
FROM
tests
left join (
select
MIN(created_on) as created_on,
test_id,
id,
assignedto_id
from
test_changes
group by
test_id
) tc on tests.id = tc.test_id
LEFT JOIN users ON tc.assignedto_id = users.id
LEFT JOIN cases ON tests.case_id = cases.id
LEFT JOIN statuses ON tests.status_id = statuses.id
WHERE
tests.id is not null
AND tests.run_id IN (22)
AND (
tests.status_id = 3
or tests.status_id = 4
or (
tests.status_id != 3
and tc.created_on > 1620950399
)
)
GROUP BY
tests.id
ORDER BY
users.name DESC
LIMIT
15, 20
这是我尝试过的 MSSQL 查询...
SELECT
tests.*,
cases.title,
users.name,
statuses.label as status_label,
statuses.color_dark,
tc.id as change_id,
tc.created_on
FROM
tests
left join (
select
MIN(created_on) as created_on,
status_id,
test_id,
id,
assignedto_id
from
test_changes
group by
test_id
) tc on tests.id = tc.test_id
LEFT JOIN users ON tc.assignedto_id = users.id
LEFT JOIN cases ON tests.case_id = cases.id
LEFT JOIN statuses ON tests.status_id = statuses.id
WHERE
tests.id is not null
AND tests.run_id IN (22)
AND (
tests.status_id = 3
or tests.status_id = 4
or (
tests.status_id != 3
and tc.created_on > 1620950399
)
)
GROUP BY
tests.id
ORDER BY
users.name DESC OFFSET 15 ROWS FETCH NEXT 20 ROWS ONLY
它抛出以下错误...
列 'test_changes.status_id' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。
有人可以帮我解决错误并形成这个 MSSQL 查询吗?
解决方案
即使您在 mysql 中的第一个查询也会给您同样的错误,当您分组时,您无法选择未聚合的列或 group by 的一部分。
所以看起来你也需要按assignedto_id和test_id分组:
select
MIN(created_on) as created_on,
status_id,
test_id,
--id, <-- removed this column , looks not used in query
assignedto_id
from
test_changes
group by
test_id, status_id,assignedto_id -- < adding new columns to group by
) tc on ....
它可能不是您正在寻找的,但可以让您了解它是如何工作的
推荐阅读
- powershell - 试图通过 Powershell 打印一个目录
- xcode12 - 项目未在 Xcode 12.5 中运行
- javascript - React:如何将函数内部的数组传递给返回(JSX)
- google-play - 亚马逊相当于 Google Play 的“测试卡,总是拒绝”
- javascript - 平滑缩放画布
- vue.js - 在 web 哈希历史模式下使用 Vue 预渲染插件和 Vue Router
- android - OpenCV Android Studio 模块导入问题
- c++ - Clang ASTContext::mergeTypes 函数的用途?复合类型?
- redux - 如何从 redux 迁移到 redux 工具包
- git - git rev-parse origin/branch_name 随机失败,并显示“致命:不明确的参数......未知的修订或路径不在工作树中”