Concat在语句中使用case时结果

时间:2017-07-24 16:08:39

标签: mysql sql

我已经看到这个问题出现了,看到它回答了很多次,但不完全是我需要的方式。我有以下查询

SELECT DISTINCT ia.UserName, ia.FirstName, ia.LastName, ia.`Password`,
CASE ipt.Code
    WHEN ipt.Code LIKE "%CORP_FILE%" THEN "ROLE_GAAP"
    WHEN ipt.Code LIKE "%RR_SUMMARY%" THEN "ROLE_RR"
END 
AS "role"
FROM 
    iCTrunk.Account ia, 
    iCTrunk.AccountGroup ig,
    iCTrunk.asscAccountAccountGroup iaaag, 
    iCTrunk.asscNodeAccountGroup ianag, 
    iCTrunk.asscNodeProjectType ianpt, 
    iCTrunk.ProjectType ipt 
WHERE ia.Id = iaaag.AccountId 
AND iaaag.AccountGroupId = ianag.AccountGroupId
AND ianag.NodeId = ianpt.NodeId 
AND ianpt.ProjectTypeId = ipt.Id
AND ia.UserName = '<some user here>'

查询中有两种可能的结果集,大多数用户只返回1.问题是如果用户是管理员,则返回两个查询结果。我试图找出一种方法来group_concat“角色”字段,这样我只得到一个返回的行。由于验证登录页面正在读取行结果,因此处理单个返回的结果会更容易。

提前谢谢。

1 个答案:

答案 0 :(得分:2)

只需添加group_concat语法和group by;并且我将distinct移动到group_concat中,因此您只能在“Role”字段中获得0-2结果。

SELECT ia.UserName, ia.FirstName, ia.LastName, ia.`Password`,
GROUP_CONCAT(DISTINCT CASE ipt.Code
    WHEN ipt.Code LIKE "%CORP_FILE%" THEN "ROLE_GAAP"
    WHEN ipt.Code LIKE "%RR_SUMMARY%" THEN "ROLE_RR"
END) AS "role"
FROM 
    iCTrunk.Account ia, 
    iCTrunk.AccountGroup ig,
    iCTrunk.asscAccountAccountGroup iaaag, 
    iCTrunk.asscNodeAccountGroup ianag, 
    iCTrunk.asscNodeProjectType ianpt, 
    iCTrunk.ProjectType ipt 
WHERE ia.Id = iaaag.AccountId 
AND iaaag.AccountGroupId = ianag.AccountGroupId
AND ianag.NodeId = ianpt.NodeId 
AND ianpt.ProjectTypeId = ipt.Id
AND ia.UserName = '<some user here>'
GROUP BY ia.UserName, ia.FirstName, ia.LastName, ia.`Password`

在case语句中的“END”之后和group_concat的')'之后,你可以把......   ORDER BY ipt.code ASC SEPARATOR ','如果您希望名称采用,分隔符的一致顺序。只是想确保你更了解group_concat()语法。