如何编写一个显示成员1和2的电影数量的SQL?
MID =会员ID FID =电影ID 下表说明:议员1名单上有2,3,5,17,21部电影。议员2在他的名单上有5,14,18部电影。
1. MID ------ | FID
2. M000001 | F000002
3. M000001 | F000003
4. M000001 | F000005
5. M000001 | F000021
6. M000002 | F000005
7. M000002 | F000014
8. M000002 | F000018
9. M000003 | F000001
10. M000003 | F000004
11. M000003 |F000024
*对不起的桌子感到抱歉。
答案 0 :(得分:3)
如果您想要所有对的数字,只需进行自我加入:
select t1.mid, t2.mid, count(*)
from table as t1 inner join
table as t2
on t1.fid = t2.fid and t1.mid < t2.mid
group by t1.mid, t2.mid;
如果您想将此限制为仅限两个成员,您可以执行以下操作:
select count(*)
from table as t1 inner join
table as t2
on t1.fid = t2.fid and
t1.mid = 1 and
t2.mid = 2;
答案 1 :(得分:0)
子查询是一种方式。
SELECT COUNT(*) FROM t1 t
WHERE EXISTS (SELECT 1 FROM t1 WHERE Mid = 2 AND Fid = t.Fid)
AND Mid = 1