如何使用CQL在表中添加两个列值?

时间:2016-03-14 15:58:49

标签: cassandra cql

我需要将两个值一起添加以使用CQL创建第三个值。有没有办法做到这一点?我的表格中包含number_of_xnumber_of_y列,我正在尝试创建total。我使用set命令对表进行了更新,如下所示:

UPDATE my_table
SET total = number_of_x + number_of_y ;

当我跑步时,我收到消息说:

no viable alternative at input ';'.

1 个答案:

答案 0 :(得分:1)

docs。赋值是以下之一:

column_name = value
set_or_list_item = set_or_list_item ( + | - ) ...
map_name = map_name ( + | - ) ...
map_name = map_name ( + | - ) { map_key : map_value, ... } 
column_name [ term ] = value
counter_column_name = counter_column_name ( + | - ) integer

并且您不能在同一个表中混合计数器和非计数器列,因此您在单个语句中描述的内容是不可能的。但是你可以在写之前做一下阅读:

CREATE TABLE my_table ( total int, x int, y int, key text PRIMARY KEY )
INSERT INTO my_table (key, x, y) VALUES ('CUST_1', 1, 1);
SELECT * FROM my_table WHERE key = 'CUST_1';

 key    | total | x | y
--------+-------+---+---
 CUST_1 |  null | 1 | 1

UPDATE my_table SET total = 2 WHERE key = 'CUST_1' IF x = 1 AND y = 1;

 [applied]
-----------
      True

SELECT * FROM my_table WHERE key = 'CUST_1';

 key    | total | x | y
--------+-------+---+---
 CUST_1 |     2 | 1 | 1

如果从IF开始更新x或y,SELECT子句将处理并发问题。如果appliedFalse,您可以再次重试。

我在这种情况下的建议是,您的应用程序只需读取xy,然后在本地添加,因为它会更好地执行。

如果您真的希望C *为您添加,则2.2 +中有sum aggregate function,但需要稍微更新您的架构:

CREATE TABLE table_for_aggregate (key text, type text, value int, PRIMARY KEY (key, type));

INSERT INTO table_for_aggregate (key, type, value) VALUES ('CUST_1', 'X', 1);
INSERT INTO table_for_aggregate (key, type, value) VALUES ('CUST_1', 'Y', 1);

SELECT sum(value) from table_for_aggregate WHERE key = 'CUST_1';

 system.sum(value)
-------------------
                 2
相关问题