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

如何在单条SQL查询中将多列国家编码替换为对应国家名称

实现方案

你现有代码存在两处问题:

  • JOIN关联条件逻辑错误,不能直接将国家编码与国家名称做匹配关联
  • 仅关联了1次country表,只能完成第一个国家编码的替换

你需要对trip表的3个国家编码字段,分别关联country表即可实现需求,SQL语句如下:

SELECT 
    t.trip_id,
    c1.country_name AS country_name,
    c2.country_name AS country_name2,
    c3.country_name AS country_name3
FROM trip t
LEFT JOIN country c1 ON t.country_code = c1.country_code
LEFT JOIN country c2 ON t.country_code2 = c2.country_code
LEFT JOIN country c3 ON t.country_code3 = c3.country_code

逻辑说明

  • 给trip表起别名t,三次关联country表时分别起别名c1/c2/c3,分别匹配trip表的三个国家编码字段
  • 全程使用LEFT JOIN可保证即使某一行的某个国家编码为空,对应的行程记录也不会被过滤,对应国家名称字段会返回NULL
  • 如果需要把NULL替换为空字符串显示,可以使用COALESCE函数处理:COALESCE(c3.country_name, '') AS country_name3

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 10:45:04