Added support for UNION and UNION ALL (#96)

This commit is contained in:
Dr. Patrick Urbanke (劉自成)
2025-11-23 23:55:42 +01:00
committed by GitHub
parent 7e4fa42bd9
commit 287ac58bf6
49 changed files with 2162 additions and 210 deletions

View File

@@ -29,6 +29,7 @@ Welcome to the sqlgen documentation. This guide provides detailed information ab
- [sqlgen::inner_join, sqlgen::left_join, sqlgen::right_join, sqlgen::full_join](joins.md) - How to join different tables
- [sqlgen::insert](insert.md) - How to insert data within transactions
- [sqlgen::select_from](select_from.md) - How to read data from a database using more complex queries
- [sqlgen::unite and sqlgen::unite_all](unite.md) - How to combine results from multiple SELECT statements
- [sqlgen::update](update.md) - How to update data in a table
## Other Operations

80
docs/unite.md Normal file
View File

@@ -0,0 +1,80 @@
# `unite` and `unite_all`
The `unite` and `unite_all` functions allow you to combine the results of multiple `SELECT` statements into a single result set.
## `unite`
The `unite` function corresponds to the SQL `UNION` operator. It combines the result sets of two or more `SELECT` statements and removes duplicate rows.
### Example
```cpp
struct User1 {
std::string name;
int age;
};
struct User2 {
std::string name;
int age;
};
const auto s1 = sqlgen::select_from<User1>("name"_c, "age"_c);
const auto s2 = sqlgen::select_from<User2>("name"_c, "age"_c);
const auto united = sqlgen::unite<std::vector<User1>>(s1, s2);
```
## `unite_all`
The `unite_all` function corresponds to the SQL `UNION ALL` operator. It combines the result sets of two or more `SELECT` statements, including all duplicate rows.
### Example
```cpp
struct User1 {
std::string name;
int age;
};
struct User2 {
std::string name;
int age;
};
const auto s1 = sqlgen::select_from<User1>("name"_c, "age"_c);
const auto s2 = sqlgen::select_from<User2>("name"_c, "age"_c);
const auto united = sqlgen::unite_all<std::vector<User1>>(s1, s2);
```
## Nesting in `SELECT` statements
You can use the result of a `unite` or `unite_all` operation as a subquery in a `SELECT` statement.
### Example
```cpp
const auto united = sqlgen::unite<std::vector<User1>>(s1, s2);
const auto sel = sqlgen::select_from(united.as("u"), "name"_c, "age"_c);
```
## Nesting in `JOIN` statements
You can also use the result of a `unite` or `unite_all` operation as a subquery in a `JOIN` statement.
### Example
```cpp
struct Login {
int id;
std::string username;
};
const auto united = sqlgen::unite<std::vector<User1>>(s1, s2);
const auto sel = select_from<Login, "t1">("id"_t1, "username"_t1) |
inner_join<"t2">(united, "username"_t1 == "name"_t2) |
where("id"_t1 == 1) | to<std::vector<Login>>;
```