Mysql行转化为列,使用IF优化查询
我有以下查询:
SELECT a.rank AS rank, concat( m.prenom, ' ', m.nom ) AS name, d.department
FROM `0_area` AS a
LEFT JOIN 0_member AS m ON a.user_id = m.id
LEFT JOIN 0_depart AS d ON a.user_id = d.user_id
WHERE a.sec_id = 2
AND (a.rank = 'mod' OR a.rank = 'adm')
AND d.department IN ( 75, 92 )
上面的查询返回三列,命名 rank |名称 |部门
并且它正在工作,针对部门的每个级别都有一个单独的行。
rank | name | department
mod | Steven Smith | 75
mod | Jeremy Roy | 92
adm | Vincent Jones | 75
我需要的是将所有这些信息放在一行中,因为我需要将其作为另一个更大查询的一部分,即仅返回一行。
我想到了 group_concat,并有两列,一列用于 mod,一列用于 adm。如果有多个 mod(给定示例为 75、92),它们将以逗号分隔。
mod | adm
Steven Smith, Jeremy Roy | Vincent Jones
我说清楚了吗?谢谢朋友们。
I have this following query:
SELECT a.rank AS rank, concat( m.prenom, ' ', m.nom ) AS name, d.department
FROM `0_area` AS a
LEFT JOIN 0_member AS m ON a.user_id = m.id
LEFT JOIN 0_depart AS d ON a.user_id = d.user_id
WHERE a.sec_id = 2
AND (a.rank = 'mod' OR a.rank = 'adm')
AND d.department IN ( 75, 92 )
The above query is returning me three columns, naming rank | name | department
and it's working, with a separate row for each rank against a department.
rank | name | department
mod | Steven Smith | 75
mod | Jeremy Roy | 92
adm | Vincent Jones | 75
What I need, is to get all those information in one row, because I need to have it as a part of another bigger query, that is returning one row only.
I thought of group_concat, and to have two columns, one for mod and one for adm. In case there are multiple mods (in 75, 92 for the given example), they will be comma separated.
mod | adm
Steven Smith, Jeremy Roy | Vincent Jones
Have I been clear? Thanks friends.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的东西:
Something like:
一些谷歌搜索告诉我,我需要这个 sql:
@ToonMariner 这解决了这个查询的问题,但是,我仍然需要将两个查询放在一起。也许我会为此创建一篇新帖子。
Some googling told me that I need this sql:
@ToonMariner This solves the problem for this query, however, I will still need to put two queries together. Probably I will create a new post for this one.