【问题标题】:Update table using with temp CTE使用临时 CTE 更新表
【发布时间】:2022-10-05 16:46:54
【问题描述】:
%sql
with temp1 as 
(
  select req_id from table1 order by timestamp desc limit 8000000
)
    
update table1  set label = \'1\'  where req_id in temp1 and req_query like \'%\\<\\/script\\>%\' 

update table1  set label = \'1\'  where req_id in temp1 and req_query like \'%aaaaa%\' 
update table1  set label = \'1\'  where req_id in temp1 and req_query like \'%bbbb%\' 

收到错误:

com.databricks.backend.common.rpc.DatabricksExceptions$SQLExecutionException:org.apache.spark.sql.catalyst.parser.ParseException: 不匹配的输入 \'in\' 期望 {, \';\'}(第 6 行,第 93 行)

有人可以建议吗?问数据库同样的问题会更便宜吗?

select req_id from table1 order by timestamp desc limit 8000000

    标签: sql apache-spark apache-spark-sql common-table-expression delta-lake


    【解决方案1】:

    这是不允许的:where req_id in temp1temp1 不是一个列表,而是一个查询的结果,应该像另一个表一样使用。
    你可能宁愿写这样的东西:

    update table1
       set label = '1'
     where req_id in (select req_id from table1 order by timestamp desc limit 8000000)
       and req_query like '%\<\/script\>%' 
    

    【讨论】:

    • 如果我有多次这种情况:更新 table1 set label = '1' where req_id in (select req_id from table1 order by timestamp desc limit 8000000) and req_query like '%\<\/script\>%' update table1 set label = '1' where req_id in (select req_id from table1 order by timestamp desc limit 8000000) and req_query like '%or 1=1%' it will query every time the database...
    • 抱歉,我不明白您的意思,但是您应该更新您的第一篇文章以添加此精度,使用正确的格式会更容易理解
    • 编辑我的问题。
    • 我明白了......无论如何,cte 在你的情况下没有任何用处。我宁愿考虑一个循环并根据我上面建议的查询构建一个动态查询(like 语句中的字符串将是一个参数)
    【解决方案2】:

    您可以将 update 与 join 一起使用,而不是 IN 子句。 Delta 不支持使用内部联接更新表,但我认为您可以使用 MERGE。像这样的东西:

    WITH temp1 AS (
      SELECT req_id FROM table1 ORDER BY timestamp DESC LIMIT 8000000
    )
    
    MERGE INTO table1 a 
    USING temp1 b
    ON (a.req_id = b.req_id)
    WHEN MATCHED THEN
    UPDATE SET a.label = CASE WHEN a.req_query LIKE '%\<\/script\>%' THEN '1'
                              WHEN a.req_query LIKE '%aaaaa%'        THEN '2'
                              WHEN a.req_query LIKE '%bbbb%'         THEN '3'
                              ELSE a.label 
                         END
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-15
      • 2021-07-05
      • 2015-11-09
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 2014-06-03
      相关资源
      最近更新 更多