我正在尝试更改数据库中的某些记录,但可惜我的sql知识有点有限。在网上搜索和阅读内容之后,我设法编写了一条select语句,在其中可以找到要更新的记录,但是我不明白编写更新语句来执行此操作的逻辑。我必须做几条类似的更新声明,以便我自己能弄清楚其余部分
这是我的选择语句:
SELECT
MG.id,
MG.status,
MG.fin,
MG.execDateTime,
EXISTS
(
SELECT 1
FROM Mtask T
JOIN MTaskHis TH ON TH.t_id= T.id
WHERE T.tg_id = MG.id
AND YEAR(TH.dateTime) = 2019
) AS hasExecStart,
NMG.id,
NMG.execDateTime,
EXISTS
(
SELECT 1
FROM Mtask T
JOIN MTaskHis TH ON TH.t_id = T.id
WHERE T.tg_id = NMG.id
AND YEAR(TH.dateTime) = 2019
) AS hasExecNext
FROM Management_Group MG
JOIN MT_Groupman MTGM ON
MG.tgm_id = MTGM.id
LEFT JOIN Management_Group NMG ON MTGM.id =
NMG.tgm_id AND YEAR(NMG.execDateTime) = 2019
JOIN Management_Man MM ON MTGM.man_id = MM.id
JOIN Location L ON MM.location_id = L.id
WHERE L.org_id = 69
AND MG.stat != 'DELETED'
AND YEAR(MG.execDateTime) = 2018
AND MM.Type= 9
AND MG.fin != 1
AND EXISTS
(
SELECT 1
FROM Mtask T
WHERE T.tg_id = MG.id
AND T.stat = 'execution'
)
HAVING hasExecNext = 0 AND hasExecStart = 1
我知道sql中的标准更新:
UPDATE <TABLENAME>
SET <fieldName> = <value>
WHERE <conditons>
除了我不知道如何将我做出的选择语句转换为更新语句,原因是: -在更新语句中将现有别名放在何处 -我也不明白何时或何地将所有JOINS放入from语句中 -怎么样
进行这样的联合更新的最佳方法是什么?
答案 0 :(得分:0)
在UPDATE中,您可以将要更新的表加入到包含当前查询的子查询中。
UPDATE YourTable t
JOIN
(
<< add your query here >>
) q ON q.SomeKeyField = t.SomeKeyField
SET t.FieldName = q.FieldNameFromSubquery,
t.OtherFieldName = q.OtherFieldNameFromSubquery