1

My data is like this:

data1_qqq_no_abc_ccc
data1_qqq_abc_ccc
data2_qqq_no_abc_ccc
data2_qqq_abc_ccc
data3_qqq_no_abc_ccc
data4_qqq_no_abc_ccc
data4_qqq_abc_ccc

...

Now I want to get the fields where data has substring _no_abc_ccc, but doesn't have _abc_ccc. In the above example, its data3

I am trying to create a query for it. rough one is

select SUBSTRING_INDEX(name, 'abc', 1)  
from table1 
where SUBSTRING_INDEX(name, 'abc', 1) not LIKE "%no" 
  and NOT IN (select SUBSTRING_INDEX(name, '_no_abc', 1) 
              from table 
              where name LIKE "%no_abc");
jarlh
  • 42,561
  • 8
  • 45
  • 63
Harsh Sharma
  • 10,942
  • 2
  • 18
  • 29

1 Answers1

5

Something like this (?)

create table t (
    col text
);

insert into t
values
('data1_qqq_no_abc_ccc'),
('data1_qqq_abc_ccc'),
('data2_qqq_no_abc_ccc'),
('data2_qqq_abc_ccc'),
('data3_qqq_no_abc_ccc'),
('data4_qqq_no_abc_ccc'),
('data4_qqq_abc_ccc');

select f from (
    select SUBSTRING_INDEX(col, '_', 1) as f, SUBSTRING_INDEX(col, '_', -3) as s from t
) tt
group by f
having 
count(case when s = 'no_abc_ccc' then 1 end) > 0
and
count(case when s like '%qqq_abc%' then 1 end)  = 0

demo

Harsh Sharma
  • 10,942
  • 2
  • 18
  • 29
Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236
  • @jarlh - I know this feeling )) – Oto Shavadze Sep 25 '18 at 18:46
  • @OtoShavadze thanks alot for the answer. But just realized the data format is more weird than I wrote and the above answer is not working for the exact data format. I reedited the question. So sorry for the trouble. – Harsh Sharma Sep 25 '18 at 18:56