You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SQL左连接技术求助:关联两个查询结果获取指定字段

SQL左连接解决方案

直接将两个查询作为子查询,通过LEFT JOIN关联,关联键为schema和表名(注意Sql1中的tablename对应Sql2中的table字段),保留Sql1的所有数据,匹配Sql2的description字段,未匹配则显示中文“空”。

最终SQL语句

SELECT 
    s1.schema,
    s1.tablename AS table,
    s1.tbl_cmmt,
    COALESCE(s2.description, '空') AS description
FROM (
    -- 原Sql1查询
    SELECT DISTINCT schema, tablename, tbl_cmmt
    FROM test.a
    WHERE tbl_cmmt IS NOT NULL
      AND schema IS NOT NULL
) s1
LEFT JOIN (
    -- 原Sql2查询
    SELECT schema, table, description 
    FROM test_descr
    JOIN test_class ON test_descr.objoid = test_class.oid
    JOIN test_namespace ON test_class.relnamespace = test_namespace.oid
    WHERE kind = 'r'
) s2 
    ON s1.schema = s2.schema 
    AND s1.tablename = s2.table;

关键说明

  • 使用LEFT JOIN确保Sql1的所有记录被保留,即使在Sql2中没有匹配项
  • 关联条件同时匹配schema和表名字段(Sql1的tablename与Sql2的table对应)
  • 用COALESCE函数将未匹配到的NULL替换为中文“空”,满足翻译要求
  • 将两个原查询包装为子查询并赋予别名s1、s2,方便关联和字段引用

测试结果(对应给定输入数据)

schematabletbl_cmmtdescription
testsampletest tabletable
test1sample1test table 2空

内容的提问来源于stack exchange,提问作者Ram

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 02:46:18