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

MySQL多条件查询:提取无逗号分隔街道字段的SQL方案求助

Solution for Extracting Street Names from physicalDeliveryOfficeName

Got it, let's sort out this issue! The problem with your current query is that when there's no comma in the physicalDeliveryOfficeName value, LOCATE(',', physicalDeliveryOfficeName) returns 0. Using that in LEFT(..., 0-1) results in an empty string because you're asking for a negative length.

Here's how to fix it by handling both comma-containing and comma-free cases:

Option 1: Using IF Function (MySQL-compatible)

SELECT 
  IF(LOCATE(',', physicalDeliveryOfficeName) > 0,
     LEFT(physicalDeliveryOfficeName, LOCATE(',', physicalDeliveryOfficeName) - 1),
     physicalDeliveryOfficeName) AS street_name
FROM contacts
GROUP BY street_name;

Option 2: Using CASE Statement (More Readable, Works Across Most Databases)

SELECT 
  CASE
    WHEN LOCATE(',', physicalDeliveryOfficeName) > 0 THEN
      LEFT(physicalDeliveryOfficeName, LOCATE(',', physicalDeliveryOfficeName) - 1)
    ELSE
      physicalDeliveryOfficeName
  END AS street_name
FROM contacts
GROUP BY street_name;

How It Works

  • When LOCATE finds a comma (returns a value greater than 0), we extract everything before the comma just like your original query did.
  • When there's no comma (LOCATE returns 0), we just use the entire physicalDeliveryOfficeName value since it's already the street name.

If you're using a database like SQL Server instead of MySQL, replace LOCATE with CHARINDEX—the logic stays exactly the same.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 16:07:35