简体   繁体   English

SQL 获取单词仅出现一次的列中的字段

[英]SQL get fields in a column where a word appears only once

So say I have this table:所以说我有这张桌子:

  -- column --
  word1
  word2
  word3 word4
  word
  

How do I get only the fields from this colum where 'word' appears only once?如何仅从该列中获取“单词”仅出现一次的字段? Like this:像这样:

  -- colum --
  word1
  word2
  word

I am using PostgreSQL.我正在使用 PostgreSQL。

Thanks in advance!提前致谢!

One option uses string functions like so:一种选择使用字符串函数,如下所示:

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

The idea is to replace all occurrences of "word" in the string, and take the difference of the resulting string with the original.这个想法是替换字符串中所有出现的“word”,并获取结果字符串与原始字符串的差异。 If the difference is 4, then we know there was only one match.如果差值为 4,那么我们知道只有一场比赛。

You can use the char_length of the column and use it as follows:您可以使用列的char_length并按如下方式使用它:

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

I interpret the question as your wanting values that only consist of one word.我将此问题解释为您想要的值仅包含一个单词。 This is another way of saying that there is no space:这是没有空间的另一种说法:

select *
from t
where col not like '% %';

If you happen to have empty strings (but not NULL values) on rows and you don't want those, you can ensure that there is a value using:如果您碰巧在行上有空字符串(但不是NULL值)并且您不想要这些,您可以使用以下方法确保有一个值:

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

That does not seem necessary based on your sample data.根据您的样本数据,这似乎没有必要。

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

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