我的数据库中有一个mysql表,如下所示

 company_id | bill_month |
 134        |Apr
 134        |May
 134        |Jun
 134        |Jul
 134        |Aug2k19
 134        |Sep2k19
 391        |Aug2k19
 391        |Sep2k19


现在我想要获取所有公司共用的几个月,我想要的结果如下所示

 bill_months|
 Aug2k19    |
 Sep2k19    |


我尝试对以下查询使用自我加入

 SELECT DISTINCT a.bill_month FROM bf_monthly_bill AS a INNER JOIN bf_monthly_bill AS b
 on a.bill_month=b.bill_month WHERE a.company_id IN('134','391')

最佳答案

您可以按bill_month分组并在HAVING子句中设置条件:

SELECT bill_month
FROM bf_monthly_bill
WHERE company_id IN ('134','391')
GROUP BY bill_month
HAVING COUNT(DISTINCT company_id) = 2

关于mysql - 如何从相同的表获取不同ID的公共(public)记录?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58407424/

10-09 17:39