如何 select 匹配行并在相同 table 上匹配其 ID 和日期

how to select matching row and match its ID and Date on the same table

我有以下示例数据

id   dt  a
1    1   token 
1    1   stuff 
1    2   at
2    1   token
2    1   stuff 
2    1   store
3    1   token
3    2   stuff
4    1   stuff
4    1   at

我想 return 每一行都包含“token”以及通过 id 和 dt 观察进行的任何匹配。预期输出如下

 id   dt  a
1    1   token 
1    1   stuff 
2    1   token
2    1   stuff 
2    1   store
3    1   token

我试过这个:

SELECT a.*
FROM stuff AS a JOIN
stuff AS b ON (a.id=b.id AND a.dt=b.dt)
WHERE a.a="token";

但它只是将 a 中的值更改为“令牌”,最好的方法是什么?

嗯。 . .我认为 exists 做你想做的事:

select s.*
from stuff s
where s.a = 'token' or
      exists (select 1 from stuff s2 where s2.id = s.id and s2.dt = s.dt and s2.a = 'token');

您可以加​​入table对抗自身以获得您想要的结果。例如:

select a.*
from stuff a
join stuff b on b.id = a.id and b.dt = a.dt 
where b.a = 'token'

我现在意识到你的解决方案几乎是正确的。您过滤了错误的 table。就是这样。