我有一些公司和成员的组合
Member Table
id company_id companymember
1 1 john
2 1 Tam
3 2 haya
4 1 lee
5 3 kih
6 3 wild
7 3 cream
8 3 earth
我想要的是
the 3 member names which belonging to the company which has more than two members
我想要的是这样的
company_id 2只有1个成员,第3行未被选中
company_id 3有4个成员,因此未选择第8行
我的目标
1 1 john
2 1 Tam
4 1 lee
5 3 kih
6 3 wild
7 3 cream
我可以做到,先拿起company_ids然后 通过脚本和fetch循环每个id。
但是这样,它执行sql多次。
有没有什么好办法在MySql上用一句话SQL ??
执行此操作答案 0 :(得分:0)
试试这个
select id,company_id,companyMember
from (Select id
,company_id
,companyMember
,Row_Number() OVER(PARTITION BY company_id ORDER By company_id) AS TotalCount
from MemberTable
) as Table1
where TotalCount <=3 and Company_id in(
Select Company_id
from MemberTable
group by Company_id
having COUNT(Company_id) >=3
)
order by id