普雷斯托
select *
from (select l.id
,count(*) as cnt
from Table2 cross join unnest (link) as l(id)
group by l.id
) t2
where t2.id in (select id from Table1)
order by id
presto:default> select *
-> from (select l.id
-> ,count(*) as cnt
-> from Table2 cross join unnest (link) as l(id)
-> group by l.id
-> ) t2
-> where t2.id in (select id from Table1)
-> order by id;
id | cnt
----+-----
1 | 7
2 | 5
3 | 4
(3 rows)
PostgreSQL的演示
create table Table1 (id int);
create table Table2 (arr int[]);
insert into Table1 values
(1),(2),(3)
;
insert into Table2 values
(array[1,5]),(array[1,3]),(array[1,2,3]),(array[2,3])
,(array[1,2,4]),(array[1,2]),(array[1,3,5]),(array[1,2,4])
;
select *
from (select unnest(arr) as id
,count(*) as cnt
from Table2
group by id
) t2
where t2.id in (select id from Table1)
order by id
+----+-----+
| id | cnt |
+----+-----+
| 1 | 7 |
+----+-----+
| 2 | 5 |
+----+-----+
| 3 | 4 |
+----+-----+
「數組」是什麼意思?這不是原生的SQL數據類型。 –
@ luke.samuel.mccarthy我建議在這裏放一些更詳細的表格描述,或DDL描述表格的樣子。這將有助於理解問題。 – Kamil
你可以請張貼一些樣品的兩個表 – Tajinder