有 2 个表 table a
和 table b
,
table A
- id
(主键)
table B
- aId
(外键)、userId
、date
例如:
表A
|id|
|--|
|1|
|2|
|3|
表 B
|aId (foreign key)|userId|
|--|--|
|1|1|
|1|2|
|2|1|
|3|3|
需要获取包含 1 和 2 id
的 userId
在下面的 SQL 中使用 in 进行了尝试,但返回一个但不是两个都返回
SELECT ta.id
FROM tableA ta
JOIN tableB tb ON ta.id = tb.taId
WHERE tb.userId in (1,2);
答案 0 :(得分:1)
使用相交的一种方式。
select taid from tableb where userid = 1
intersect
select taid from tableb where userid = 2
另一个使用 group by
select
taid
from
tableb
where
userid in (1, 2)
group by
taid
having
count(distinct userid) > 1
答案 1 :(得分:0)
with data
as (select 1 as userid
union all
select 2 as userid
)
select m.tableaid
,count(distinct n.userid)
from data m
left join tableB n
on m.userid=n.userid
group by m.tableaid
having count(distinct n.userid)=2