mysql中的拆分匹配字符串

t2a7ltrp  于 2021-06-20  发布在  Mysql
关注(0)|答案(3)|浏览(355)

我想选择范围地址相等的所有行
table

id    Address
    1   5419-5436 East hancock Street, Somerset, VA
    2   251 West Churchill Road, Arlington, TX
    3   981-981 Main Street , norman, OK
    4   615-615 Mountain Ave, Bridgewater, NJ

输出

id  Address
3   981-981 Main Street , norman, OK
4   615-615 Mountain Ave, Bridgewater, NJ

地址号码981-981615-615相等。5419-5436没有被选中,因为它的地址范围不同。

2sbarzqh

2sbarzqh1#

select * from your_table where
SUBSTRING_INDEX( SUBSTRING_INDEX(Address,'-',-1),' ',1)=SUBSTRING_INDEX(Address,'-',1)
cidc1ykv

cidc1ykv2#

试试这个:
样本数据:

create table tbl(txt varchar(100));
insert into tbl values
('5419-5436 East hancock Street, Somerset, VA'),
('251 West Churchill Road, Arlington, TX'),
('981-981 Main Street , norman, OK'),
('615-615 Mountain Ave, Bridgewater, NJ');

下面是t-sql。在内部查询中,我们选择整个地址和提取的范围地址,过滤掉那些没有连字符的记录( - ). 我们分开了 RangeAddress 用连字符( - )并将其与 RangeAddress . 在此基础上,我们过滤结果集。

select txt from (
    select txt,
           substring(txt, 1, locate(' ', txt) - 1) RangeAddress
    from tbl
    where locate('-', substring(txt, 1, locate(' ', txt) - 1)) > 0
) a 
where substring(RangeAddress, 1, locate('-', RangeAddress) - 1) = 
                 substring(RangeAddress, locate('-', RangeAddress) + 1);
ybzsozfc

ybzsozfc3#

您可以使用子字符串索引来选择“-”两侧的部分并进行比较:

SELECT * 
FROM Table1
WHERE SUBSTRING_INDEX(Address, '-', 1) = SUBSTRING_INDEX(SUBSTRING_INDEX(Address, '-', -1), ' ', 1)

示例数据的输出:

id    Address
3     981-981 Main Street , norman, OK 
4     615-615 Mountain Ave, Bridgewater, NJ

注意:此代码假定数字后面有空格。

相关问题