如何使用SQL获取具有另一个表的所有值的相同ID?

时间:2018-04-10 01:04:44

标签: sql postgresql

表一叫做PublisherSupply

| Publisher | Book |  
| ------------------------|  
| A | Pride and Prejudice |  
| B | 1984 |  
| B | The Great Gatsby |  
| B | Pride and Prejudice |  
| C | 1984 |  
| C | The Great Gatsby |  
| D | Beloved |  
| D | 1984 |  
| D | The Great Gatsby |  
| E | Beloved |  
| E | 1984 |  
| E | The Great Gatsby |  
| E | Sense and Sensibility | 

表2称为订单

| Orders |  
| ---------------- |  
| Beloved |  
| The Great Gatsby |  
| 1984 |

现在,我想查找在订单列表中发布所有图书的所有发布商。 即D and E

2 个答案:

答案 0 :(得分:1)

您必须使用RIGHT JOIN,因为只需要显示在订单表中提及图书的发布商。

SELECT a.publisher
    FROM publishersupply a RIGHT JOIN orders b 
    ON a.book=b.book
    WHERE a.publisher IN ('D','E')
    GROUP BY a.publisher,a.book,b.book;

答案 1 :(得分:0)

以下是一种使用joingroup byhaving的方法:

select p.publisher
from publisher p join
     orders o
     on p.book = o.book
group by p.publisher
having count(*) = (select count(*) from orders o);