如何在M:N关系的绑定表中的一列上构造带有AND限制的查询?

时间:2015-10-07 13:58:01

标签: mysql sql database

我在作者和出版商之间有约束表。每个作者都可以连接到许多发布者,一个发布者可以连接到许多作者。它是M:N的关系。因此我有绑定表。当然,也可以是作者只与其中一个出版商联系。

我想选择连接到Publisher1并同时连接到Publisher2的所有作者。我不希望结果集作者只是连接到Publisher1或只是连接到Publisher2。 Simply Publisher1 AND Publisher2。

我尝试了这个查询:

SELECT author_id FROM author_publisher where publisher_id = 1 AND where publisher_id = 2

但它没有用。我得到了空位。

我试图使用相交:

SELECT author_id FROM author_publisher where publisher_id = 1 
Intersect 
Select author_id FROM author_publisher where publisher_id = 2

但我使用的是MySQL,似乎不支持。

有没有人有任何建议如何构建这样的查询?

2 个答案:

答案 0 :(得分:1)

您可以使用不相关的子查询...不是最高效的方式,但您可以尝试:

SELECT author_id FROM author_publisher WHERE publisher_id = 1
and author_id in (SELECT author_id FROM author_publisher WHERE publisher_id = 2)

答案 1 :(得分:0)

您可以使用针对绑定表的两个连接来执行此操作:

SELECT author.* FROM author
  JOIN author_publisher AS ap1
    ON ap1.author_id = author.author_id AND ap1.publisher_id = 1
  JOIN author_publisher AS ap2
    ON ap2.author_id = author.author_id AND ap2.publisher_id = 2

或等效地使用JOIN ... USING ()语法,并将publisher_id条件移至WHERE感知:

SELECT author.* FROM author
  JOIN author_publisher AS ap1 USING (author_id)
  JOIN author_publisher AS ap2 USING (author_id)
 WHERE ap1.publisher_id = 1 AND ap2.publisher_id = 2

如果您只需要ID,您甚至可以将其简化为绑定表与其自身的单个连接:

SELECT author_id
  FROM author_publisher AS ap1
  JOIN author_publisher AS ap2 USING (author_id)
 WHERE ap1.publisher_id = 1 AND ap2.publisher_id = 2