代码之家  ›  专栏  ›  技术社区  ›  Khairu Aqsara

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

  •  0
  • Khairu Aqsara  · 技术社区  · 6 年前

    光环, 我有两个办公桌,有邮政编码和办公室

    offices_postcodes = id,postcode,office_id
    offices   = id,offices,department 
    

    情况是: 例子:

    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。

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

    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 
    

    数据邮政编码:

    id  postcode    office_id
    1   0100036     271 
    2   0100036     275 
    3   0100035     271 
    4   0100037     271
    5   0100037     275 
    6   0100039     271 
    

    数据办公室

    id      offices     department_id
    271     A           1
    275     B           1
    

    预期结果

    postcode 
    0100035
    0100039
    
    1 回复  |  直到 6 年前
        1
  •  1
  •   D-Shih    6 年前

    我想你可以试着用 JOIN 打开并连接条件 op.office_id = o.id

    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

    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  |
    

    View on DB Fiddle