在MySql db中的同一个表上更新字段

时间:2016-09-05 09:02:41

标签: mysql

在表格doTable中,我需要将字段Priority设置为1,其中单个CBT_ID存在这些条件:

  1. CEO> 0
  2. SUM(CE_TOT)> 50
  3. 我尝试过这个SQL查询但没有成功,因为我有错误。

    mysql> UPDATE `doTable` pd
    INNER JOIN `doTable` pd2 ON (
        pd.CBT_ID = pd2.CBT_ID
        AND pd.CEO > 0
        AND SUM(pd.CE_TOT) > 50
    )
    SET pd.Priority = 1;
    1111 - Invalid use of group function
    

    如何解决这个问题?

3 个答案:

答案 0 :(得分:4)

您不能在sum子句中使用where之类的聚合函数。在不知道表结构的情况下编写查询很困难,但如果有多个行具有相同的CBT_ID,则可以尝试以下方法:

UPDATE `doTable`
SET Priority = 1 
where CBT_ID in 
    (select CBT_ID from `doTable` 
     where CEO > 0 
     group by CBT_ID 
     having SUM(CE_TOT) > 50
     );

答案 1 :(得分:2)

试试这个SQL

{
   "users": {
      "settings": {
         "index": {
            "analysis": {
               "filter": {
                  "shingle_filter": {
                     "max_shingle_size": "2",
                     "min_shingle_size": "2",
                     "output_unigrams": "true",
                     "type": "shingle"
                  },
                  "edgeNGram_filter": {
                     "type": "nGram",
                     "min_gram": "1",
                     "max_gram": "20"
                  }
               },
               "analyzer": {
                  "autocomplete_query_analyzer": {
                     "filter": [
                        "standard",
                        "asciifolding",
                        "lowercase"
                     ],
                     "tokenizer": "standard"
                  },
                  "autocomplete_index_analyzer": {
                     "filter": [
                        "standard",
                        "asciifolding",
                        "lowercase",
                        "shingle_filter",
                        "edgeNGram_filter"
                     ],
                     "tokenizer": "standard"
                  }
               }
            },
            "number_of_shards": "1",
            "number_of_replicas": "1"
         }
      }
   }
}

{
   "users": {
      "mappings": {
         "data": {
            "properties": {
               "name": {
                  "type": "string",
                  "analyzer": "autocomplete_index_analyzer",
                  "search_analyzer": "autocomplete_query_analyzer"
               }
            }
         }
      }
   }
}

如果出现错误,请尝试将AND更改为HAVING。

或者一次运行两个查询

UPDATE doTable
SET Priority = 1
WHERE (
SELECT *
FROM doTable
WHERE CEO > 0
AND SUM(CE_TOT) > 50
);

答案 2 :(得分:1)

试试这个:

UPDATE `doTable` AS r
JOIN (
    SELECT
        CBT_ID,
        SUM(CE_TOT) AS q,
        CEO
    FROM
        `doTable`
    WHERE
        CEO > 0
    GROUP BY
        CBT_ID
    HAVING
        q > 50
) AS grp ON r.CBT_ID = grp.CBT_ID
SET r.Priority = 1
WHERE
    grp.CEO > 0
AND grp.q > 50;