chiachan
chiachan
Published on 2024-09-19 / 5 Visits
0

clickhouse通关攻略(三) - 快速入门

clickhouse通关攻略(三) - 快速入门

创建表

使用 CREATE TABLE 定义新表。在 ClickHouse 中,典型的 SQL DDL 命令同样适用,唯一的补充是 ClickHouse 中的表需要一个 ENGINE 子句。
使用 MergeTree 利用 ClickHouse 的性能优势

CREATE TABLE my_first_table
(
    user_id UInt32,
    message String,
    timestamp DateTime,
    metric Float32
)
ENGINE = MergeTree
PRIMARY KEY (user_id, timestamp)

插入数据

使用熟悉的 INSERT INTO TABLE 命令,但重要的是要理解,

  • 每次插入 MergeTree 表时,ClickHouse 会在存储中创建一个我们称之为 part 的部分。这些部分稍后会在后台由 ClickHouse 合并。
  • 对于 MergeTree 引擎系列的表,ClickHouse 默认为自动 去重插入
INSERT INTO my_first_table (user_id, message, timestamp, metric) VALUES
    (101, 'Hello, ClickHouse!',                                 now(),       -1.0    ),
    (102, 'Insert a lot of rows per batch',                     yesterday(), 1.41421 ),
    (102, 'Sort your data based on your commonly-used queries', today(),     2.718   ),
    (101, 'Granules are the smallest chunks of data read',      now() + 5,   3.14159 )

更新数据

使用 ALTER TABLE...UPDATE 命令更新表中的行

ALTER TABLE my_first_table
UPDATE message = 'updated'
WHERE user_id = 101

UPDATE my_first_table SET message = 'updated'
WHERE user_id = 101

删除数据

使用 ALTER TABLE 命令删除行

ALTER TABLE my_first_table DELETE WHERE user_id = 101

DELETE FROM my_first_table WHERE user_id = 101

要删除表中的所有数据,使用 TRUNCATE TABLE [<database].]<table> 命令更有效。此命令也可以在 ON CLUSTER 上执行。

查询表

使用任何 SQL 数据库一样编写 SELECT 查询

SELECT *
FROM my_first_table
ORDER BY timestamp

从其他源导入数据