【问题标题】:Make new column which is incremented by it's order创建按顺序递增的新列
【发布时间】:2015-04-02 12:53:52
【问题描述】:

我需要为我的表 Products 创建新列 -> 称为 Order(新列)。并且使用 rails 迁移我需要添加新列并立即设置它的订单号,但这需要通过 product_id 完成。

我的意思是我需要类似的东西:

product_id |顺序

1 ------------> 1

1 ------------> 2

1 ------------> 3

2 ------------> 1

2 ------------> 2

有办法吗?

编辑: 您的 SQL 语法有错误;检查与您的 MySQL 服务器版本相对应的手册,以在第 15 行的 ''order' = t1.'order'' 附近使用正确的语法:

update product_submissions t
      join (
       select
       id,
       product_id,
       'order' from  (
          select id,
          product_id,
          @rn:= if(@prev = product_id,@rn:=@rn+1,1) as 'order',
          @prev:=product_id
          from product_submissions,
          (select @rn:=0,@prev:=0)r
          order by product_id,id
         )x
      )t1 on t1.id=t.id set t.'order' = t1.'order'

【问题讨论】:

  • 您需要添加一些关于您的架构的信息,例如订单、产品及其关系,以及何时设置上述数据等。
  • 表中是否有主键?
  • 此外,您发布的查询未使用正确的引号。使用反引号将列名括起来。

标签: mysql sql ruby-on-rails migration rails-migrations


【解决方案1】:

考虑以下

mysql> create table test (id int ,product_id int);
Query OK, 0 rows affected (0.14 sec)

mysql> insert into test values (1,1),(2,1),(3,1),(4,2),(5,2);

现在让我们创建订单

select 
product_id,
`order` from ( 
  select 
  product_id, 
  @rn:= if(@prev = product_id,@rn:=@rn+1,1) as `order`,
  @prev:=product_id from test,(select @rn:=0,@prev:=0)r
  order by product_id,id 
)x ;

这会给你一些东西

+------------+-------+
| product_id | order |
+------------+-------+
|          1 |     1 |
|          1 |     2 |
|          1 |     3 |
|          2 |     1 |
|          2 |     2 |
+------------+-------+

现在让我们在更新命令中使用,但在此之前让我们添加列(在您的情况下它已经存在)

mysql> alter table test add column `order` int ;
Query OK, 5 rows affected (0.29 sec)

mysql> select * from test ;
+------+------------+-------+
| id   | product_id | order |
+------+------------+-------+
|    1 |          1 |  NULL |
|    2 |          1 |  NULL |
|    3 |          1 |  NULL |
|    4 |          2 |  NULL |
|    5 |          2 |  NULL |
+------+------------+-------+
5 rows in set (0.00 sec)

最后是更新命令

update test t 
join (
 select 
 id,
 product_id,
 `order` from  ( 
    select id,
    product_id, 
    @rn:= if(@prev = product_id,@rn:=@rn+1,1) as `order`,
    @prev:=product_id 
    from test,(select @rn:=0,@prev:=0)r
    order by product_id,id 
   )x
)t1 on t1.id=t.id set t.`order` = t1.`order`

mysql> select * from test ;
+------+------------+-------+
| id   | product_id | order |
+------+------------+-------+
|    1 |          1 |     1 |
|    2 |          1 |     2 |
|    3 |          1 |     3 |
|    4 |          2 |     1 |
|    5 |          2 |     2 |
+------+------------+-------+
5 rows in set (0.00 sec)

【讨论】:

  • 好吧,它给了我错误:(编辑问题中的错误消息
  • 不是单引号'order'它的反引号` `
猜你喜欢
  • 1970-01-01
  • 2023-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-27
  • 2017-03-27
  • 2015-05-23
  • 1970-01-01
相关资源
最近更新 更多