MySQL查询的子字符串

时间:2019-07-04 15:05:01

标签: mysql database

我有两个相互关联的表。问题出在我想进行查询以显示每个请求者上的所有departement_name,但departement上的tbl_request却不止一个并且用逗号分隔时。

tbl_request:

enter image description here

tbl_departement:

enter image description here

是否可以这样制作?如果不是,什么是最好的方法,至少是最接近的方法。

request_id    sow    request_type   date   requestor   departement
==================================================================
11          qwer       jk      2019-07-06  Lutfi       DevOps,Business Dev
12          adga       gadga   2019-07-06  sfags       RnD,DevOps

到目前为止,我对子字符串什么也没做。我只是在玩普通的查询。

SELECT
    tbl_request.request_id AS request_id,
    tbl_request.sow AS sow,
    tbl_request.request_type AS request_type,
    tbl_request.date AS date,
    tbl_request.requestor AS requestor,
    tbl_departement.departement_name AS departement_name
FROM
    `tbl_request`
LEFT JOIN 
    tbl_departement ON tbl_request.departement = tbl_departement.departement_id

1 个答案:

答案 0 :(得分:0)

加入2个表并按请求分组。然后使用group_concat()

select 
  r.request_id, r.sow, r.request_type, r.date, r.requestor,
  group_concat(d.department_name) departement
from tbl_request r inner join tbl_departement d
on concat('%,', r.department, ',%') like concat('%,', d.department_id, ',%')
group by r.request_id, r.sow, r.request_type, r.date, r.requestor, r.department

请参见demo
结果:

| request_id | sow  | request_type | date       | requestor  | departement         |
| ---------- | ---- | ------------ | ---------- | ---------- | ------------------- |
| 12         | qwer | jk           | 2019-07-06 | Lufti Aldi | Business Dev,DevOps |
| 13         | adga | gadga        | 2019-07-13 | sfags      | RnD,DevOps          |