以下是使用C++语言实现两表左连接的示例代码:

#include <iostream>
#include <unordered_map>
#include <vector>

using namespace std;

vector<vector<int>> leftJoin(vector<vector<int>>& table1, vector<vector<int>>& table2) {
    unordered_map<int, vector<vector<int>>> mp;
    for(auto& row : table2) {
        int key = row[0];
        mp[key].push_back(row);
    }

    vector<vector<int>> result;
    for(auto& row : table1) {
        int key = row[0];
        if(mp.find(key) != mp.end()) {
            for(auto& r : mp[key]) {
                result.push_back({key, row[1], r[1]});
            }
        } else {
            result.push_back({key, row[1], 0});
        }
    }

    return result;
}

int main() {
    vector<vector<int>> table1 = {{1, 10}, {2, 20}, {3, 30}, {4, 40}};
    vector<vector<int>> table2 = {{1, 100}, {2, 200}, {3, 300}, {5, 500}};

    vector<vector<int>> result = leftJoin(table1, table2);

    for(auto& row : result) {
        for(auto& col : row) {
            cout << col << " ";
        }
        cout << endl;
    }

    return 0;
}

其中,leftJoin函数接受两个参数table1table2,分别代表两个表格。该函数使用unordered_maptable2中所有以第一列为键的行按照键值分组,然后遍历table1,对于每一行,如果在mp中找到了相应的键值,则将table1中的第二列和table2中的第二列合并成一行添加到结果中;否则将table1中的第一列和第二列以及0(表示table2中没有对应的行)合并成一行添加到结果中。最后返回结果。

main函数中,我们定义了两个表格,并调用leftJoin函数将它们进行左连接,得到结果并输出。

两表进行左连接,两表各选择前两列作为键值,最快的效率,重新生成对应C++代码

原文地址: https://www.cveoy.top/t/topic/vRn 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录