在一个表中使用逗号分隔的字符串id连接两个表

wfveoks0  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(359)

这是具有 branch name 以及 employee 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是行政或艺术雇员

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

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

我希望输出像上面那样 n 地点,有多少行政人员和艺术人员在场?
这是sqlfiddle演示的地方http://sqlfiddle.com/#!9/27aa51/1号

uyto3xhc

uyto3xhc1#

尽管您应该实现规范化。
但是,这里仍然有一个查询,它将使用嵌套查询为您工作:

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

首先是艺术,然后是高管(按字母顺序,艺术排在第一位)

相关问题