mysql SQL UPDATE TABLE通过其他表的SELECT查询

6ioyuze2  于 2023-01-16  发布在  Mysql
关注(0)|答案(1)|浏览(168)

我有bd hf3和5表有:active_preset,具有列(标识符、预设标识符)preset,具有列(标识符、笔标标识符、趋势标识符、分形、间隔_向上)birja,具有列(标识符、名称)trend,具有列(标识符、名称)uq_active_preset,具有列(标识符、笔标、趋势、分形、间隔_向上)
在表preset中,我有一些记录。其中一些记录在表active_preset中通过外键preset_id存在。在表active_preset中,一些记录存在一次,一些记录存在多次。
我需要用表active_preset中的记录更新表uq_active_preset,忽略重复的记录(如果存在)。
我确实从active_preset进行了查询,它运行良好:

SELECT 
    b.name AS birja, p.fractal AS fractal , tre.name AS trend, p.interval_up AS interval_up  
FROM hf3.active_preset AS ap
INNER JOIN hf3.preset AS p on p.id = ap.preset_id
INNER JOIN hf3.birja AS b on b.id = p.birja_id
INNER JOIN hf3.trend AS tre on tre.id = p.trend_id
GROUP BY b.name, p.fractal, tre.name, p.interval_up
HAVING COUNT(*) >= 1

但我不知道如何更新uq_active_preset
我尝试了这个,它返回语法错误:1064:

UPDATE hf3.uq_active_preset uap SET 
  uap.birja = st.birja ,
  uap.fractal = st.fractal,
  uap.trend = st.trend,
  uap.interval_up = st.interval_up,
 FROM (SELECT b.name AS birja, p.fractal AS fractal , tre.name AS trend, p.interval_up AS interval_up  
        from hf3.active_preset AS ap
        INNER JOIN hf3.preset AS p on p.id = ap.preset_id
        INNER JOIN hf3.birja AS b on b.id = p.birja_id
        INNER JOIN hf3.trend AS tre on tre.id = p.trend_id
        GROUP BY b.name, p.fractal, tre.name, p.interval_up
        HAVING COUNT(*) >= 1
        ) st
y53ybaqx

y53ybaqx1#

当你使用from进行更新时,就像你用查询结果连接更新的表一样。所以,你还需要一个where语句来告诉你这两个表是在哪里连接的。另外,不要在set语句中使用更新的表的别名。你需要这样的东西:

UPDATE hf3.uq_active_preset uap SET birja=st.birja,fractal=st.fractal,trend=st.trend,interval_up=st.interval_up
 FROM (SELECT b.name AS birja, p.fractal AS fractal , tre.name AS trend, p.interval_up AS interval_up  
        from hf3.active_preset AS ap
        INNER JOIN hf3.preset AS p on p.id = ap.preset_id
        INNER JOIN hf3.birja AS b on b.id = p.birja_id
        INNER JOIN hf3.trend AS tre on tre.id = p.trend_id
        GROUP BY b.name, p.fractal, tre.name, p.interval_up
        HAVING COUNT(*) >= 1
        ) st
where uap.fkey=st.fkey

相关问题