如何在一个查询中使用SELECT和UPDATE语句?

时间:2016-05-11 15:55:44

标签: mysql sql

我有这个update查询也可以运行:

UPDATE tbname t CROSS JOIN ( SELECT related FROM tbname WHERE id = 5 ) x
    SET AcceptedAnswer = ( id = 5 )
  WHERE t.related   = x.related

我还有两个选择语句来验证某些事情。实际上我想在更新之前检查这些条件:

条件1:

(SELECT 1 FROM tbname 
  WHERE id = x.related AND
        author_id = 29
)

条件2:

(SELECT 1 FROM tbname
  WHERE id = x.related AND
       (
          ( amount IS NOT NULL AND
            NOT EXISTS ( SELECT 1 FROM tbname
                           WHERE related = x.related AND
                                 AcceptedAnswer = 1 )
          ) OR amount IS NULL
       )
)

如何将这两个条件与更新查询相结合?

以下是我迄今为止所尝试的内容,但它无法正常工作并抛出此错误:



UPDATE tbname CROSS JOIN ( SELECT related FROM tbname WHERE id = 5 ) x
SET AcceptedAnswer = ( id = 5 )
  WHERE q.related   = x.related
    AND
    (SELECT 1 FROM tbname 
      WHERE id = x.related AND
            author_id = 29
    ) AND
    (SELECT 1 FROM tbname
      WHERE id = x.related AND
            (
              ( amount IS NOT NULL AND
                NOT EXISTS ( SELECT 1 FROM tbname
                               WHERE related = x.related AND
                                     AcceptedAnswer = 1 )
              ) OR amount IS NULL
            )
    )




  

#1093 - 您无法指定目标表' tbname'用于FROM子句中的更新

2 个答案:

答案 0 :(得分:1)

似乎您的更新等同于此

update tbname as a
inner join tbname as b on a.related = b.related and b.id = 5
set AcceptedAnswer = (id =  5) 

您的查询似乎设置为true(1)对于已加入的行,id = 5的行的AccepetdAnswer等于在另一种情况下id = 5(false / 0)的行的可接受值。

供测试使用

select * from  tbname as a
inner join tbname as b on a.related = b.related and b.id = 5
and (b.related = a.id and a.author_id = 29)
and (b.related = a.id and 
          (a.amont is not null and (a.related = b.related and a.AcceptedAnswer = 1)))

答案 1 :(得分:0)

我不太确定SET子句的目的是什么(id = 5) 无论如何,这样可以避免使用交叉连接 不要使用表格" x"获得超越"相关"项目

UPDATE tbname 
SET 
    AcceptedAnswer = ( id = 5 )
WHERE  
    #THIS IS EQUIVALENT TO THE JOIN CLAUSE
    id IN ( SELECT related FROM tbname WHERE id = 5 )

    #THIS IS THE CONDITION 1 POINTING tnname    
    AND author_id = 29  

    #THIS IS THE CONDITION 2 POINTING tbname    
    AND ( 
     ( amount IS NOT NULL 
       AND NOT AcceptedAnswer = 1
     ) OR amount IS NOT NULL 
    )
;