使用 MySQL 进行关系除法

Using MySQL for relationnal division

我需要使用关系划分执行查询

我有什么:2 tables 和第 3 个 table 用于 Many-to-Many 关系

=> 会议有多个参与者,参与者可以参加多个会议

我需要什么:获得至少有给定参与者的会议

这里有一个 SQL 查询来完成这项工作:

SELECT 
  m.meeting_id,
  m.name,
  m.status
FROM meetings As m
INNER JOIN meetings_participants AS mp ON m.meeting_id = mp.meeting_id
WHERE m.status <> 'temporary' 
AND mp.participant_id IN (1, 2)
GROUP BY m.meeting_id
HAVING COUNT(DISTINCT mp.participant_id) >= 2

SQL Fiddle : http://sqlfiddle.com/#!9/8a331d/6/0

  • Question 1 : is there a way to select what I need without the 'HAVING COUNT...' part ?

  • Question 2 : and in a second query, I need the meetings with exactly the given participants, how to do it ?

Question 1 : is there a way to select what I need without the 'HAVING COUNT...' part ?

是的,您可以使用多个 JOIN,但这不是很好 solution.because 每个 mp.participant_id 都需要一个 JOIN...您拥有的查询更具可扩展性

查询

SELECT 
    m.meeting_id
 ,  m.name
 ,  m.status
FROM 
  meetings AS m
INNER JOIN meetings_participants AS mp1 ON m.meeting_id = mp1.meeting_id AND m.status <> 'temporary' AND mp1.participant_id = 1
INNER JOIN meetings_participants AS mp2 ON m.meeting_id = mp2.meeting_id AND m.status <> 'temporary' AND mp2.participant_id = 2

结果

| meeting_id |      name |    status |
|------------|-----------|-----------|
|          1 | a meeting |    active |
|          5 | e meeting | cancelled |

演示 http://sqlfiddle.com/#!9/8a331d/54

Question 2 : and in a second query, I need the meetings with exactly the given participants

您需要先为每个 meeting_participants 有两条记录

找到 COUNT

  SELECT 
   meeting_id 
  FROM 
   meetings_participants
  GROUP BY 
   meeting_id
  HAVING COUNT(*) = 2

并像这样在主查询中使用它。

查询

SELECT 
 meetings.*
FROM ( 

 SELECT 
   meeting_id
  FROM 
   meetings_participants
  WHERE
    participant_id IN(1, 2)  
   AND
    meeting_id IN(
      SELECT 
       meeting_id 
      FROM 
       meetings_participants
      GROUP BY 
       meeting_id
      HAVING COUNT(*) = 2
    )
  GROUP BY 
   meeting_id 
  HAVING COUNT(*) = 2
) 
 meetings_participants
INNER JOIN 
 meetings
ON 
 meetings_participants.meeting_id = meetings.meeting_id

结果

| meeting_id |      name |    status |
|------------|-----------|-----------|
|          5 | e meeting | cancelled |

演示http://sqlfiddle.com/#!9/8a331d/46