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

How do I add two column values in a table with CQL?

我需要将两个值相加以使用 CQL 创建第三个值。有什么办法吗?我的 table 有列 number_of_xnumber_of_y,我正在尝试创建 total。我使用如下设置命令对 table 进行了更新:

UPDATE my_table
SET total = number_of_x + number_of_y ;

当我 运行 收到回复消息时说:

no viable alternative at input ';'.

根据 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

并且您不能在同一个 table 中混合计数器和非计数器列,因此您所描述的内容不可能在单个语句中。但是你可以先读再写:

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

如果 x 或 y 自 SELECT 后更新,IF 子句将处理并发问题。如果 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