简体   繁体   中英

SQL Postgres find word first to appear among list of words in string field

I have a simple query. Looking for a word in string field like the following:

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.90 Safari/537.36 2345Explorer/9.2.1.17116

I EXPECT "CHROME" ROWS ONLY AS AN OUTPUT

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/56.0.2924.90 Chrome/537.36 2345Explorer/9.2.1.17116

I EXPECT "SAFARI" ROWS ONLY AS AN OUTPUT

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Explorer/56.0.2924.90 Safari/537.36 2345Chrome/9.2.1.17116

I EXPECT "EXPLORER" ROWS ONLY AS AN OUTPUT

Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Explorer/56.0.2924.90 Safari/537.36 2345Chrome/9.2.1.17116

I do not want "CHROME" rows as an output when I query for rows with "CHROME"

Think about Chrome only and chrome = 1 Then if I have 1-2-3, I want to output If 2-1-3 i don't want to output If 2-3-1 don't want to output

I want it only when it comes first.

I want to be able to display only field where Chrome appear first, then with another query only field where Safari is first (not this case). DO you have an idea please? beginning with the following code

 SELECT *
 FROM user_logins
 WHERE user_agent NOT LIKE '%iPhone%'
 AND user_agent NOT LIKE '%Linux; Android%'
 order BY id DESC
 LIMIT 1000

I would regex it, smth like:

so=# with c(s) as (values
 ('blahChrome/56.0.2924.90 Safari/537.36 2345')
,('blahSafariblahChromeblah')
)
select s ~ 'Chrome.*Safari', s ~ 'Safari.*Chrome',s from c;
 ?column? | ?column? |                     s
----------+----------+--------------------------------------------
 t        | f        | blahChrome/56.0.2924.90 Safari/537.36 2345
 f        | t        | blahSafariblahChromeblah
(2 rows)

You can use substring() with a pattern argument to extract the element of the form /#.#.#.#. Then compare it to 'Chrome':

select substring(x from '[^ ]*/[0-9]+[.][0-9]+[.][0-9]+[.][0-9]'),
       v.*
from (values ('Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/56.0.2924.90 Safari/537.36 2345Explorer/9.2.1.17116'),
             ('Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Safari/56.0.2924.90 Chrome/537.36 2345Explorer/9.2.1.17116')
     ) v(x)
where substring(x from '[^ ]*/[0-9]+[.][0-9]+[.][0-9]+[.][0-9]') like 'Chrome/%';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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