简单hashjoin mergejoin 完整源码
时间: 2023-11-25 09:07:47 浏览: 74
以下是简单的 Hash Join 的完整源代码(使用 C++ 实现):
```cpp
#include <iostream>
#include <unordered_map>
#include <vector>
using namespace std;
struct Record {
int id;
string name;
int age;
};
vector<Record> left_table = {
{1, "Alice", 20},
{2, "Bob", 25},
{3, "Charlie", 30},
{4, "David", 35},
};
vector<Record> right_table = {
{101, "Alice", 20},
{102, "Bob", 25},
{103, "Eve", 22},
};
void simple_hash_join() {
// Build a hash table for the left table
unordered_map<int, Record> ht;
for (const auto& r : left_table) {
ht[r.id] = r;
}
// Scan the right table and join with the hash table
for (const auto& r : right_table) {
auto it = ht.find(r.id);
if (it != ht.end()) {
// Join the two records
const auto& l = it->second;
cout << l.id << ", " << l.name << ", " << l.age << ", "
<< r.id << ", " << r.name << ", " << r.age << endl;
}
}
}
int main() {
simple_hash_join();
return 0;
}
```
以下是简单的 Merge Join 的完整源代码(使用 C++ 实现):
```cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct Record {
int id;
string name;
int age;
};
vector<Record> left_table = {
{1, "Alice", 20},
{2, "Bob", 25},
{3, "Charlie", 30},
{4, "David", 35},
};
vector<Record> right_table = {
{1, "Alice", 20},
{2, "Bob", 25},
{3, "Eve", 22},
{4, "Frank", 40},
};
void simple_merge_join() {
// Sort both tables by id
sort(left_table.begin(), left_table.end(), [](const auto& a, const auto& b) {
return a.id < b.id;
});
sort(right_table.begin(), right_table.end(), [](const auto& a, const auto& b) {
return a.id < b.id;
});
// Merge join the two tables
int i = 0, j = 0;
while (i < left_table.size() && j < right_table.size()) {
if (left_table[i].id < right_table[j].id) {
i++;
} else if (left_table[i].id > right_table[j].id) {
j++;
} else {
// Join the two records
const auto& l = left_table[i];
const auto& r = right_table[j];
cout << l.id << ", " << l.name << ", " << l.age << ", "
<< r.id << ", " << r.name << ", " << r.age << endl;
i++;
j++;
}
}
}
int main() {
simple_merge_join();
return 0;
}
```
以上代码仅供参考,实际应用中需要根据具体情况进行修改和调整。
阅读全文