我有两个相互关联的表。问题出在我想进行查询以显示每个请求者上的所有departement_name
,但departement
上的tbl_request
却不止一个并且用逗号分隔时。
tbl_request:
tbl_departement:
是否可以这样制作?如果不是,什么是最好的方法,至少是最接近的方法。
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
答案 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 |