带子查询的sql查询

lzfw57am  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(424)

我的数据如下:

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

...
现在我想得到数据有子串没有,但没有的字段。在上面的例子中,它的数据是3
我正在尝试为它创建一个查询。粗糙的是

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");
vyswwuz2

vyswwuz21#

像这样的东西(?)

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

演示

相关问题