首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >找到只属于特定办公室的相关邮政编码

找到只属于特定办公室的相关邮政编码
EN

Stack Overflow用户
提问于 2018-09-27 07:56:44
回答 1查看 26关注 0票数 0

哈洛,我有两张桌子offices_postcodes和办公室

代码语言:javascript
复制
offices_postcodes = id,postcode,office_id
offices   = id,offices,department 

情况是:一个办公室有多个邮政编码,一个邮政编码属于多个办公室,例如:

代码语言:javascript
复制
postcode 0100036 has relation with office A
postcode 0100036 has relation with office B
postcode 0100035 only has relation with office A
postcode 0100037 has relation with office A
postcode 0100037 has relation with office B
postcode 0100039 only has relation with office A

我想找到所有属于A办公室的邮政编码,但不属于B办公室,在这种情况下是0100035和0100039。

我们能做到吗?,这是我到目前为止所做的,

代码语言:javascript
复制
SELECT Count(`offices_postcodes`.postcode), 
       `offices_postcodes`.postcode 
FROM   `offices_postcodes`, 
       `offices` 
WHERE  `offices_postcodes`.office_id = `offices`.id 
       AND `offices`.department_id = 1 
       AND offices_postcodes.deleted_at IS NULL 
GROUP  BY `offices_postcodes`.postcode 
HAVING Count(`offices_postcodes`.postcode) = 1 

数据邮政编码:

代码语言:javascript
复制
id  postcode    office_id
1   0100036     271 
2   0100036     275 
3   0100035     271 
4   0100037     271
5   0100037     275 
6   0100039     271 

数据办公室

代码语言:javascript
复制
id      offices     department_id
271     A           1
275     B           1

预期结果

代码语言:javascript
复制
postcode 
0100035
0100039
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-09-27 08:08:14

我认为您可以尝试使用JOINop.office_id = o.id上的连接条件。

模式(MySQL v5.7)

代码语言:javascript
复制
CREATE TABLE offices_postcodes(
   id INT,
   postcode VARCHAR(50),
   office_id INT
);




INSERT INTO offices_postcodes VALUES (1,'0100036',271); 
INSERT INTO offices_postcodes VALUES (2,'0100036',275); 
INSERT INTO offices_postcodes VALUES (3,'0100035',271); 
INSERT INTO offices_postcodes VALUES (4,'0100037',271);
INSERT INTO offices_postcodes VALUES (5,'0100037',275); 
INSERT INTO offices_postcodes VALUES (6,'0100039',271); 

CREATE TABLE offices(
   id INT,
   postcode VARCHAR(50),
   department_id INT
);


INSERT INTO offices VALUES (271,'A',1);
INSERT INTO offices VALUES (275,'B',1);

查询#1

代码语言:javascript
复制
SELECT  op.postcode 
FROM `offices_postcodes` op JOIN `offices` o
ON op.office_id = o.id 
GROUP BY op.postcode 
having  Count(op.postcode) = 1;

| postcode |
| -------- |
| 0100035  |
| 0100039  |

关于DB Fiddle的看法

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52532109

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档