将两个用逗号分隔的字符串ID的表连接到一个表中

时间:2018-08-06 08:38:49

标签: mysql phpmyadmin

这是分支明细表,其中有branch nameemployee id在该分支上工作。

CREATE TABLE Branch_detail
   (`nid` int,`branch` varchar(15), `emp_with_department` varchar(15));

INSERT INTO Branch_detail
   (`nid`,`branch`, `emp_with_department`)
VALUES
  (1,'Mumbai', '1,2,4'),
  (2,'Banglore', '4,5');




 | nid |   branch | emp_with_department |
 |-----|----------|---------------------|
 |   1 |   Mumbai |               1,2,4 |  
 |   2 | Banglore |                 4,5 |

这是员工详细信息表,带有各自的名称。

CREATE TABLE Emp 
 (`id` int, `name` varchar(10), `Designations ` varchar(10));

INSERT INTO Emp 
 (`id`, `name`,`Designations `)
VALUES
 (1,'Rantesh', 'Executive'),
 (2,'Keith', 'Art'),
 (3,'Nikhil', 'Executive'),
 (4,'Gauresh', 'Art'),
 (5,'Sumit', 'Executive');


| id |    name | Designations |
|----|---------|--------------|
|  1 | Rantesh |  Executive   |
|  2 |   Keith |        Art   |
|  3 |  Nikhil |  Executive   |
|  4 | Gauresh |        Art   |
|  5 |   Sumit |  Executive   |

此查询我试图至少获取ID为Executive或Art员工

  SELECT  a.nid,
  GROUP_CONCAT(b.Designations ORDER BY b.id) Designations_Name
  FROM    Branch_detail a INNER JOIN Emp b
  ON FIND_IN_SET(b.id, a.emp_with_department) > 0
  GROUP   BY a.nid


| nid |  Designations_Name|
|-----|-------------------|
|   1 | Executive,Art,Art |
|   2 |     Art,Executive |

输出应为:

nid = 1的高管人数

nid = 1的艺术数量

nid = 2的高管人数

nid = 1的艺术数量

OR

| nid |  count(Designations_Name)|
|-----|--------------------------|
|   1 | 1,2,2                    |
|   2 | 1,1                      |

我希望在n位置上有这样的输出,计数中有多少位执行人员和艺术员工?

这是演示的sqlfiddle http://sqlfiddle.com/#!9/27aa51/1

1 个答案:

答案 0 :(得分:1)

尽管您应该实现Normalization

但是,仍然可以使用Nested Queries这是一个适合您的查询:

select inner_nest.nid, GROUP_CONCAT(designations_count) 
FROM (SELECT a.nid, b.Designations, COUNT(DISTINCT b.id) as designations_count 
      FROM Branch_detail a 
      INNER JOIN Emp b ON FIND_IN_SET(b.id, a.emp_with_department) > 0 
      WHERE 1 = 1 
      GROUP BY a.nid, b.Designations ) AS inner_nest 
GROUP BY inner_nest.nid 

它首先获得艺术计数,然后是高管(按字母顺序艺术首先出现)