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

如何修改SQL查询以同时返回关联的code与name字段

修改SQL查询以同时返回code和对应name

问题背景

原SQL查询:

select name from tbl1 where id in ( select id from tbl2 where code in (12,13,14,15,16))

执行后仅返回name列表:

name1
name2
name3 
etc...

需要修改查询,使其返回指定code与对应name的对应关系,示例输出:

12  name1
13  name2
14  name3
15  name4
16  name5

解决方案

基础方案(仅返回有匹配关系的记录)

用表连接替代子查询,直接从关联的两个表中取出所需字段:

select t2.code, t1.name
from tbl1 t1
inner join tbl2 t2 on t1.id = t2.id
where t2.code in (12,13,14,15,16)
  • INNER JOIN只返回两个表中id匹配的记录,确保每条结果都有对应的code和name
  • 表别名t1、t2用于简化SQL语句书写

进阶方案(保留所有指定code,无匹配时显示NULL)

如果需要确保所有12-16的code都出现在结果中(即使部分code在tbl2或tbl1中无匹配记录),可以先构造包含目标code的数据集,再进行左连接:

select c.code, t1.name
from (
    select 12 as code union all
    select 13 union all
    select 14 union all
    select 15 union all
    select 16
) c
left join tbl2 t2 on c.code = t2.code
left join tbl1 t1 on t2.id = t1.id

这种写法会返回所有指定的code,没有对应name的记录会显示NULL。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 10:45:28