【问题标题】:MYSQL UPDATE SELECT - upgrade ColumnMYSQL UPDATE SELECT - 升级列
【发布时间】:2013-10-25 03:41:48
【问题描述】:

BD Wordpress - 表:wp_term_relationships

object_id | term_taxonomy_id| term_order 1 | 23 | 0 2 | 22 | 0 3 | 23 | 0 4 | 22 | 0 5 | 23 | 0 6 | 21 | 0

我需要计算每个“类别”中有多少“产品”,并在“term_order”列中插入

例如:

object_id | term_taxonomy_id| term_order 1 | 23 | 3 2 | 22 | 2 3 | 23 | 3 4 | 22 | 2 5 | 23 | 3 6 | 21 | 1

我做了这样的事情,但它没有更新字段“term_order”:

UPDATE `letras`.`wp_term_relationships`
SET `term_order` = '2'
WHERE `wp_term_relationships`.`object_id` = '5' ;

SELECT  object_id as id_objeto, 
        COUNT(  `object_id` ) quantidade
FROM wp_term_relationships
WHERE `object_id` =  `object_id` 
GROUP BY  `term_taxonomy_id` 

【问题讨论】:

    标签: sql wordpress


    【解决方案1】:

    您可以使用子查询将表连接到自身:

    update t
    set term_order = t2.cnt
    from wp_term_relationships t
      join (
        select term_taxonomy_id, count(*) cnt
        from wp_term_relationships
        group by term_taxonomy_id
    ) t2 on t.term_taxonomy_id = t2.term_taxonomy_id;
    

    由于您使用的是 MySQL,因此应该可以:

    update wp_term_relationships 
      join (
        select term_taxonomy_id, count(*) cnt
        from wp_term_relationships
        group by term_taxonomy_id
    ) t2 on wp_term_relationships.term_taxonomy_id = t2.term_taxonomy_id
    set wp_term_relationships.term_order = t2.cnt;
    

    【讨论】:

    • 错误:1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 3 行的“from wp_term_relationships t join (select term_taxonomy_id, count(*) cn”附近使用正确的语法
    【解决方案2】:

    对不起!

    我在 phpMyAdmin 中执行:

    更新 设置 term_order = t2.cnt 从 wp_term_relationships t 加入 ( 选择 term_taxonomy_id, count(*) cnt 来自 wp_term_relationships 按 term_taxonomy_id 分组 ) t2 上 t.term_taxonomy_id = t2.term_taxonomy_id;

    错误:

    1064 - 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 3 行的“from wp_term_relationships t join (select term_taxonomy_id, count(*) cn”附近使用正确的语法

    【讨论】:

      猜你喜欢
      • 2020-07-20
      • 2010-12-29
      • 2014-03-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-14
      • 2011-05-17
      • 1970-01-01
      相关资源
      最近更新 更多