简体   繁体   English

根据 SQL 中另一个表中的值从列中提取子字符串

[英]Extract substring from column based on values from another table in SQL

In SQL (let's assume ANSI standard SQL), is it possible to extract a substring from one column, based on another table, and put this substring into another column?在 SQL 中(假设是 ANSI 标准 SQL),是否可以根据另一个表从一列中提取子字符串,并将该子字符串放入另一列中?

Example, from the following tables:示例,来自下表:

VISITS
name       summary
---------------------------------------------
john       visit to London
jack       hotel in Paris with park visits
joe        b&b in Paris with ice cream
james      holidays in London and museums
jason      visit in Milan and fashion tour

LOCATIONS
id    name
-------------
1     Paris
2     London
3     Milan
4     Berlin

The idea is to extract the location from the summary column and output the following:想法是从summary列中提取位置并输出以下内容:

VISITS
name       summary                              location
---------------------------------------------
john       visit to London                      London
jack       hotel in Paris with park visits      Paris
joe        b&b in Paris with ice cream          Paris
james      holidays in London and museums       London
jason      visit in Milan and fashion tour      Milan

You can do pattern matching:您可以进行模式匹配:

select v.*, l.name
from visits v
left join locations l on v.summary like concat('%', l.name, '%')

As commented by jarlh ANSI sql has operator ||正如 jarlh 所评论的,ANSI sql 有操作符|| for string concatenation, so, depending on your database:用于字符串连接,因此,取决于您的数据库:

select v.*, l.name
from visits v
left join locations l on v.summary like '%' || l.name || '%'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM