我正在解析存储在Sql表中的电视节目数据,该数据有两列,一列用于整个节目标题(例如系列名称),另一列用于节目的副标题(例如单个剧集标题)。然而,程序副标题也经常包含系列名称,或者在字符串的开头,或者在结尾,或者两者都包含,格式如下:
。因此,对于标题为"Horizon"和正确的副标题为"The£1000万Challenge",以下是subtitle字段中值的可能组合:
- 地平线:1000万英镑的挑战
- 1000万英镑挑战:地平线
- 地平线:1000万英镑的挑战:地平线
分隔符也可以是空格连字符,而不是冒号加空格,例如:"Horizon - the£1000万Challenge - Horizon"
本质上我想做的是,对于表中的每一行,如果subtitle包含Title列中位于subtitle开头的值(后面跟着':'或' - '),或者如果该值位于列末尾(前面跟着':'或' - '),或者两者兼有,那么更新该subtitle以删除该前缀或后缀。有人能帮我或给我指个方向吗?我不确定从哪里开始。
为什么要在subtitle字段中使用标题名称?
我认为你应该提取实际名称,然后做你想做的事情。我认为这需要大量的case语句:
update table t
set subtitle = (case when subtitle like concat(title, ':%', title)
then trim(substring_index(substring_index(subtitle, ':', 2), ':', -1)))
when subtitle like concat(title, '-%', title)
then trim(substring_index(substring_index(subtitle, '-', 2), '-', -1)))
when subtitle like concat('%:', title)
then trim(substring_index(subtitle, ':', 1))
when subtitle like concat('%-', title)
then trim(substring_index(subtitle, '-', 2))
else subtitle
end)
先在select
中测试一下。此外,在某些情况下,如果副标题名称中有连字符或冒号,这将不起作用。
我决定打破前缀&后缀到两个单独的查询,使其更容易,随着第三次检查,我已经注意到,有时节目标题是在括号前的副标题。这就是我最后使用的(后面是最后一个操作,从列中删除任何剩余的空白)。
UPDATE table
set subtitle = (case
when subtitle like concat(title,': %') /*Title: Subtitle*/
then trim(LEADING concat(title,': ') FROM subtitle)
when subtitle like concat(title,' - %') /*Title - Subtitle*/
then trim(LEADING concat(title,' - ') FROM subtitle)
when subtitle like concat('(',title,') %') /*(Title) Subtitle*/
then trim(LEADING concat('(',title,') ') FROM subtitle)
else subtitle end);
UPDATE table
set subtitle = (case
when subtitle like concat('%: ',title) /*Subtitle: Title*/
then trim(TRAILING concat(': ',title) FROM subtitle)
when subtitle like concat('% - ',title) /*Subtitle - Title*/
then trim(TRAILING concat(' - ',title) FROM subtitle)
when subtitle like concat('%(',title,') ') /*Subtitle (Title)*/
then trim(TRAILING concat('(',title,') ') FROM subtitle)
else subtitle end);
UPDATE table
set subtitle = trim(BOTH ' ' FROM subtitle);
感谢@gordon-lindoff。