【问题标题】:Cassandra select distinct and order by cqlshCassandra 选择 distinct 并按 cqlsh 排序
【发布时间】:2019-02-17 15:56:14
【问题描述】:

我是 Cassandra 和这个论坛的新手。我正在使用 cqlsh 执行 Cassandra 查询,但我不知道如何使用 Cassandra 执行像 sql select distinct a, b, c from table order by d asc 这样的查询。我能怎么做?表的结构是什么?

【问题讨论】:

    标签: cassandra sql-order-by distinct


    【解决方案1】:

    您的primary keypartition keysclustering columns 组成。

    • DISTINCT 查询只能请求分区键。
    • 聚集列支持 ORDER BY。

    假设我们有一个如下示例表,

    CREATE TABLE Sample ( 
     field1 text,
     field2 text,
     field3 text,
     field4 text,
     PRIMARY KEY ((field1, field2), field3));
    

    DISTINCT 要求所有分区键以逗号分隔。

    所以你不能运行这个查询select distinct field1 from Sample;。一个有效的表达式是select distinct field1, field2 from Sample;

    它在内部命中集群中的所有节点以查找所有分区键,因此如果您的表中有数百万个分区,我预计多个节点的性能会下降。

    默认情况下,字段 3 的记录将按升序排列。下面的查询将按 field3 的降序提供记录。

    select * from Sample where field1 = 'a' and field2 = 'b' order by field3 desc;
    

    如果您已经了解查询模式以及需要对数据进行排序的方式,则可以采用这种方式设计表格。假设您总是需要按降序排列 field3 的记录,您可以这样设计表格。

    CREATE TABLE Sample ( 
     field1 text,
     field2 text,
     field3 text,
     field4 text,
     PRIMARY KEY ((field1, field2), field3))
    WITH CLUSTERING ORDER BY (field3 DESC);
    

    现在不按顺序查询会得到同样的结果。

    您可以对多个聚集列使用 order by。但是您不能跳过订单。为了理解这一点,让我们有一个如下所示的示例表,

    CREATE TABLE Sample1 ( 
     field1 text,
     field2 text,
     field3 text,
     field4 int,
     field5 int,
     PRIMARY KEY ((field1, field2), field3, field4));
    

    我添加了一些虚拟记录。

    你可以像select * from Sample1 where field1 = 'a' and field2 = 'b' order by field3 desc, field4 desc;这样使用多个列的顺序

    注意:所有字段必须按正序 (field3 asc, field4 asc) 或负序 (field3 desc, field4 desc)。你不能这样做 (field3 asc, field4 desc),反之亦然。

    以上查询将导致此结果。

    通过写我们不能跳过 order by,我的意思是我们不能做像 select * from Sample1 where field1 = 'a' and field2 = 'b' order by field4 desc; 这样的事情

    我希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 2021-11-18
      • 2014-03-23
      • 2021-09-05
      • 1970-01-01
      • 2020-01-13
      • 2020-10-05
      • 2018-05-13
      • 2018-07-03
      • 1970-01-01
      相关资源
      最近更新 更多