SQL 获取列中某个单词只出现一次的字段

SQL get fields in a column where a word appears only once

所以说我有这个 table:

  -- column --
  word1
  word2
  word3 word4
  word
  

如何仅从该列中获取 'word' 仅出现一次的字段?像这样:

  -- colum --
  word1
  word2
  word

我正在使用 PostgreSQL。

提前致谢!

一个选项使用字符串函数,如下所示:

select *
from mytable
where char_length(col) - char_length(replace(col, 'word', '')) = char_length('word')

想法是替换字符串中所有出现的“word”,并将生成的字符串与原始字符串的差异。如果差值是 4,那么我们知道只有一个匹配项。

可以使用列的char_length,如下使用:

select * from your_table
where char_length(replace(col, 'word', '')) 
       = char_length(col) - char_length('word')

我把这个问题解释为你想要的值只有一个词。这是没有 space:

的另一种说法
select *
from t
where col not like '% %';

如果您碰巧在行上有空字符串(但不是NULL值)并且您不想要这些,您可以确保有一个值使用:

select *
from t
where col not like '% %' and col like '%_%'

根据您的示例数据,这似乎没有必要。