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

Northwind数据库:如何编写符合长度条件的客户查询并通过Union组合?

修正Northwind数据库的Union查询问题

直接给你修正后的完整SQL代码:

select customername, customers.city, customers.postalcode
from customers 
join suppliers on customers.city = suppliers.city and customers.PostalCode = suppliers.PostalCode
union
select customername, customers.city, customers.postalcode
from customers 
where length(customername) >= (select max(length(suppliername)) - 5 from suppliers)

问题说明

你之前的第二个查询条件只判断了客户名长度小于最长供应商名长度,完全没体现“最多比最长供应商名称短5个字符”的要求。

正确的逻辑是先算出最长供应商名称的长度,再减去5得到阈值,只要客户名长度大于等于这个阈值,就符合“最多短5个字符”的要求——对应你用硬编码>33的场景,如果最长供应商名是38,38-5=33,要是你实际需要的是客户名长度严格大于33,那就把条件里的>=改成>就行:

where length(customername) > (select max(length(suppliername)) - 5 from suppliers)

补充提示

  • 用子查询(select max(length(suppliername)) -5 from suppliers)能动态计算阈值,不用硬编码数值,后续供应商表数据变化时也不用手动修改这个条件。
  • UNION会自动去重,如果你的业务需要保留重复的记录,可以换成UNION ALL,不过一般作业里用UNION就够了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 09:35:03