Sql 在m:m关系中查找字符串的第一个匹配项

Sql 在m:m关系中查找字符串的第一个匹配项,sql,postgresql,Sql,Postgresql,在PostgreSQL中,表a和表b是m:m关系-如何查找所有出现的字符串: 出现在a.string和b.string列中 并在b.string中出现,然后根据ab.id的顺序出现在a.string中 例如,hello出现在a.string和b.string列中,并根据ab.id的顺序首先出现在b.string中,因此hello将作为结果返回 比如: select * from table ab left join table a on (a.id = ab.a_id) left join ta

在PostgreSQL中,表a和表b是m:m关系-如何查找所有出现的字符串:

出现在a.string和b.string列中 并在b.string中出现,然后根据ab.id的顺序出现在a.string中 例如,hello出现在a.string和b.string列中,并根据ab.id的顺序首先出现在b.string中,因此hello将作为结果返回

比如:

select *
from table ab
left join table a on (a.id = ab.a_id)
left join table b on (b.id = ab.b_id)
-- pseudo: 
  -- where b.string "hello" occurs first
  -- and a.string "hello" also exists
order by ab.id


ab.id | ab.a_id | ab.b_id | a.string | b.string 
-----------------------------------------------------
  1      63        59       'good bye'   > 'hello' -- appears first here
  2      75        67       > 'hello'    'sounds good'
  3      77        78       'have fun'   'awesome'
编辑:

基本上,用户应该首先看到a.string列形式的字符串,然后是b.string列形式的字符串。如果b.string实例第一次出现,我们应该返回它

我需要说明两种情况,其中不满足上述条件

1 b.string满足在a.string之前出现的条件,但它不是a.string的hello的第一个实例-即,在第1行中,a.string和b.string是hello,但第2行满足了b.string的hello出现在a.string之前的条件:

2当b.string为NULL时,a.string出现在某个其他点上,则在a.string之前出现的b.string的任何其他行条件应为FALSE

ab.id | ab.a_id | ab.b_id | a.string | b.string 
-----------------------------------------------------
  1      63        59       'hello'      NULL
  2      75        67       'good bye'   'hello'
  3      77        78       'hello'      'awesome'

你有两个条件。我想到了存在和不存在:

select ab.*
from ab
where not exists (select 1
                  from ab ab2
                  where ab2.astring = ab.bstring and
                        ab2.id < ab.id
                 ) and  -- no earlier "a"s
      exists (select 1
              from ab ab2
              where ab2.astring = ab.bstring 
             )          -- another "a"

这让我有点困惑——表ab只是a和b的m:m表,因此ab.string不存在。另外,为了简洁起见,您是否只是省略了连接?
select ab.*
from ab
where not exists (select 1
                  from ab ab2
                  where ab2.astring = ab.bstring and
                        ab2.id < ab.id
                 ) and  -- no earlier "a"s
      exists (select 1
              from ab ab2
              where ab2.astring = ab.bstring 
             )          -- another "a"