未验证 提交 1e20c2bc 编写于 作者: B BayoNet 提交者: GitHub

DOCAPI-5760: Join engine docs. EN review. RU translation (#6234)

上级 a5069939
......@@ -12,7 +12,7 @@ CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
) ENGINE = Join(join_strictness, join_type, k1[, k2, ...])
```
See the detailed description of [CREATE TABLE](../../query_language/create.md#create-table-query) query.
See the detailed description of the [CREATE TABLE](../../query_language/create.md#create-table-query) query.
**Engine Parameters**
......@@ -20,7 +20,7 @@ See the detailed description of [CREATE TABLE](../../query_language/create.md#cr
- `join_type`[JOIN type](../../query_language/select.md#select-join-types).
- `k1[, k2, ...]` – Key columns from the `USING` clause that the `JOIN` operation is made with.
Set the parameters `join_strictness` and `join_type` without quotes, for example, `Join(ANY, LEFT, col1)`. They must match the `JOIN` operation that the table will be used for. If parameters don't match, ClickHouse doesn't throw an exception and may return incorrect data.
Enter `join_strictness` and `join_type` parameters without quotes, for example, `Join(ANY, LEFT, col1)`. They must match the `JOIN` operation that the table will be used for. If the parameters don't match, ClickHouse doesn't throw an exception and may return incorrect data.
## Table Usage
......@@ -29,14 +29,18 @@ Set the parameters `join_strictness` and `join_type` without quotes, for example
Creating the left-side table:
```sql
CREATE TABLE id_val(`id` UInt32, `val` UInt32) ENGINE = TinyLog;
INSERT INTO id_val VALUES (1,11)(2,12)(3,13);
CREATE TABLE id_val(`id` UInt32, `val` UInt32) ENGINE = TinyLog
```
```sql
INSERT INTO id_val VALUES (1,11)(2,12)(3,13)
```
Creating the right-side `Join` table:
```sql
CREATE TABLE id_val_join(`id` UInt32, `val` UInt8) ENGINE = Join(ANY, LEFT, id);
CREATE TABLE id_val_join(`id` UInt32, `val` UInt8) ENGINE = Join(ANY, LEFT, id)
```
```sql
INSERT INTO id_val_join VALUES (1,21)(1,22)(3,23)
```
......@@ -53,7 +57,7 @@ SELECT * FROM id_val ANY LEFT JOIN id_val_join USING (id) SETTINGS join_use_null
└────┴─────┴─────────────────┘
```
Retrieving the data from the `Join` table, specifying the join key value:
As an alternative, you can retrieve data from the `Join` table, specifying the join key value:
```sql
SELECT joinGet('id_val_join', 'val', toUInt32(1))
......@@ -66,12 +70,12 @@ SELECT joinGet('id_val_join', 'val', toUInt32(1))
### Selecting and Inserting Data
You can use `INSERT` to add data to the table. For the `ANY` strictness, data for duplicated keys are ignored. For the `ALL` strictness, all rows are kept.
You can use `INSERT` queries to add data to the `Join`-engine tables. If the table was created with the `ANY` strictness, data for duplicate keys are ignored. With the `ALL` strictness, all rows are added.
You cannot perform the `SELECT` query directly from the table. Use one of the following ways:
You cannot perform a `SELECT` query directly from the table. Instead, use one of the following methods:
- Place the table at the right side in a `JOIN` clause.
- Call the [joinGet](../../query_language/functions/other_functions.md#other_functions-joinget) function, which allows to extract data from the table as from a dictionary.
- Place the table to the right side in a `JOIN` clause.
- Call the [joinGet](../../query_language/functions/other_functions.md#other_functions-joinget) function, which lets you extract data from the table the same way as from a dictionary.
### Limitations and Settings
......@@ -83,12 +87,12 @@ When creating a table, the following settings are applied:
- [join_overflow_mode](../settings/query_complexity.md#settings-join_overflow_mode)
- [join_any_take_last_row](../settings/settings.md#settings-join_any_take_last_row)
The table can't be used in `GLOBAL JOIN` operations.
The `Join`-engine tables can't be used in `GLOBAL JOIN` operations.
## Data Storage
Data for the `Join` tables is always located in RAM. When inserting rows into the table, ClickHouse writes the data blocks to the directory on disk to be able to restore them on server restart.
`Join` table data is always located in the RAM. When inserting rows into a table, ClickHouse writes data blocks to the directory on the disk so that they can be restored when the server restarts.
At the abnormal server restart, the block of data on the disk might be lost or damaged. In this case, you may need to manually delete the file with damaged data.
If the server restarts incorrectly, the data block on the disk might get lost or damaged. In this case, you may need to manually delete the file with damaged data.
[Original article](https://clickhouse.yandex/docs/en/operations/table_engines/join/) <!--hide-->
......@@ -668,9 +668,9 @@ So, result of function depends on partition of data to blocks and on order of da
## joinGet('join_storage_table_name', 'get_column', join_key) {#other_functions-joinget}
Gets data from the [Join](../../operations/table_engines/join.md) table using the specified join key.
Gets data from [Join](../../operations/table_engines/join.md) tables using the specified join key.
Supports only tables created with `ENGINE = Join(ANY, LEFT, <join_keys>)` statement.
Only supports tables created with the `ENGINE = Join(ANY, LEFT, <join_keys>)` statement.
## modelEvaluate(model_name, ...)
Evaluate external model.
......
# Join
Представляет собой подготовленную структуру данных для JOIN-а, постоянно находящуюся в оперативке.
Подготовленная структура данных для использования в операциях [JOIN](../../query_language/select.md#select-join).
## Создание таблицы
```
CREATE TABLE [IF NOT EXISTS] [db.]table_name [ON CLUSTER cluster]
(
name1 [type1] [DEFAULT|MATERIALIZED|ALIAS expr1] [TTL expr1],
name2 [type2] [DEFAULT|MATERIALIZED|ALIAS expr2] [TTL expr2],
) ENGINE = Join(join_strictness, join_type, k1[, k2, ...])
```
Смотрите подробное описание запроса [CREATE TABLE](../../query_language/create.md#create-table-query).
**Параметры движка**
- `join_strictness`[строгость JOIN](../../query_language/select.md#select-join-strictness).
- `join_type`[тип JOIN](../../query_language/select.md#select-join-types).
- `k1[, k2, ...]` – ключевые столбцы секции `USING` с которыми выполняется операция `JOIN`.
Вводите параметры `join_strictness` и `join_type` без кавычек, например, `Join(ANY, LEFT, col1)`. Они должны быть такими же как и в той операции `JOIN`, в которой таблица будет использоваться. Если параметры не совпадают, ClickHouse не генерирует исключение и может возвращать неверные данные.
## Использование таблицы
### Пример
Создание левой таблицы:
```sql
CREATE TABLE id_val(`id` UInt32, `val` UInt32) ENGINE = TinyLog
```
```sql
INSERT INTO id_val VALUES (1,11)(2,12)(3,13)
```
Создание правой таблицы с движком `Join`:
```sql
CREATE TABLE id_val_join(`id` UInt32, `val` UInt8) ENGINE = Join(ANY, LEFT, id)
```
```sql
INSERT INTO id_val_join VALUES (1,21)(1,22)(3,23)
```
Join(ANY|ALL, LEFT|INNER, k1[, k2, ...])
Объединение таблиц:
```sql
SELECT * FROM id_val ANY LEFT JOIN id_val_join USING (id) SETTINGS join_use_nulls = 1
```
```text
┌─id─┬─val─┬─id_val_join.val─┐
│ 1 │ 11 │ 21 │
│ 2 │ 12 │ ᴺᵁᴸᴸ │
│ 3 │ 13 │ 23 │
└────┴─────┴─────────────────┘
```
В качестве альтернативы, можно извлечь данные из таблицы `Join`, указав значение ключа объединения:
```sql
SELECT joinGet('id_val_join', 'val', toUInt32(1))
```
```text
┌─joinGet('id_val_join', 'val', toUInt32(1))─┐
│ 21 │
└────────────────────────────────────────────┘
```
Параметры движка: `ANY|ALL` - строгость, `LEFT|INNER` - тип.
Эти параметры (задаются без кавычек) должны соответствовать тому JOIN-у, для которого будет использоваться таблица. k1, k2, ... - ключевые столбцы из секции USING, по которым будет делаться соединение.
### Выборка и вставка данных
Для добавления данных в таблицы с движком `Join` используйте запрос `INSERT`. Если таблица создавалась со строгостью `ANY`, то данные с повторяющимися ключами игнорируются. Если задавалась строгость `ALL`, то добавляются все строки.
Из таблиц нельзя выбрать данные с помощью запроса `SELECT`. Вместо этого, используйте один из следующих методов:
- Используйте таблицу как правую в секции `JOIN`.
- Используйте функцию [joinGet](../../query_language/functions/other_functions.md#other_functions-joinget), которая позволяет извлекать данные из таблицы таким же образом как из словаря.
### Ограничения и настройки
При создании таблицы, применяются следующие параметры :
- [join_use_nulls](../settings/settings.md#settings-join_use_nulls)
- [max_rows_in_join](../settings/query_complexity.md#settings-max_rows_in_join)
- [max_bytes_in_join](../settings/query_complexity.md#settings-max_bytes_in_join)
- [join_overflow_mode](../settings/query_complexity.md#settings-join_overflow_mode)
- [join_any_take_last_row](../settings/settings.md#settings-join_any_take_last_row)
Таблицы с движком `Join` нельзя использовать в операциях `GLOBAL JOIN`.
Таблица не может использоваться для GLOBAL JOIN-ов.
## Хранение данных
В таблицу можно вставлять данные INSERT-ом, аналогично движку Set. В случае ANY, данные для дублирующихся ключей будут проигнорированы; в случае ALL - будут учитываться. Из таблицы нельзя, непосредственно, делать SELECT. Единственная возможность чтения - использование в качестве "правой" таблицы для JOIN.
Данные таблиц `Join` всегда находятся в RAM. При вставке строк в таблицу ClickHouse записывает блоки данных в каталог на диске, чтобы их можно было восстановить при перезапуске сервера.
Хранение данных на диске аналогично движку Set.
При аварийном перезапуске сервера блок данных на диске может быть потерян или повреждён. В последнем случае, может потребоваться вручную удалить файл с повреждёнными данными.
[Оригинальная статья](https://clickhouse.yandex/docs/ru/operations/table_engines/join/) <!--hide-->
......@@ -637,4 +637,10 @@ SELECT filesystemAvailable() AS "Free space", toTypeName(filesystemAvailable())
Принимает на вход состояния агрегатной функции и возвращает столбец со значениями, которые представляют собой результат мёржа этих состояний для выборки строк из блока от первой до текущей строки. Например, принимает состояние агрегатной функции (например, `runningAccumulate(uniqState(UserID))`), и для каждой строки блока возвращает результат агрегатной функции после мёржа состояний функции для всех предыдущих строк и текущей. Таким образом, результат зависит от разбиения данных по блокам и от порядка данных в блоке.
## joinGet('join_storage_table_name', 'get_column', join_key) {#other_functions-joinget}
Получает данные из таблиц [Join](../../operations/table_engines/join.md) по ключу.
Поддержаны только таблицы, созданные запросом с `ENGINE = Join(ANY, LEFT, <join_keys>)`.
[Оригинальная статья](https://clickhouse.yandex/docs/ru/query_language/functions/other_functions/) <!--hide-->
......@@ -506,7 +506,7 @@ FROM <left_subquery>
Вместо `<left_subquery>` и `<right_subquery>` можно указать имена таблиц. Это эквивалентно подзапросу `SELECT * FROM table`, за исключением особого случая таблицы с движком [Join](../operations/table_engines/join.md) – массива, подготовленного для присоединения.
**Поддерживаемые типы `JOIN`**
#### Поддерживаемые типы `JOIN` {#select-join-types}
- `INNER JOIN` (or `JOIN`)
- `LEFT JOIN` (or `LEFT OUTER JOIN`)
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册