我在MySQL
代理
Agent Type
--------------------------
Bob 1,2,3,4
Sam 2,3,4
类型
Type Name
--------------------------
1 Gold
2 Platinum
3 Silver
4 Supreme
我的问题是如何使用select statement
Agent Type
-----------------------------------------
Bob Gold, Platinum, Silver, Supreme
Sam Platinum, Silver, Supreme
答案 0 :(得分:1)
这会将数组拆分为行,然后使用group concat将其放回到数组中。这个查询的缩小是你需要增加表号,以防有> agent.type列中最长数组中的5个值。
SELECT agent, GROUP_CONCAT(name ORDER BY name)
as type
FROM (
SELECT
agent.agent,
type.name
FROM
(SELECT 1 as n
UNION ALL SELECT 2
UNION ALL SELECT 3
UNION ALL SELECT 4
UNION ALL SELECT 5) numbers
INNER JOIN agent
ON CHAR_LENGTH(agent.type)-
CHAR_LENGTH(REPLACE(agent.type, ',', ''))>=numbers.n-1
INNER JOIN type
ON type.type =
SUBSTRING_INDEX(SUBSTRING_INDEX(agent.type, ',', numbers.n), ',', -1)
) tab
GROUP BY agent
ORDER BY agent;
答案 1 :(得分:0)
正如上面提到的那些人你应该转换代理表,所以Type列不是逗号分隔的字符串,你希望每个数字有一行,所以在这个例子中,Agent表将是七行长你的查询将很简单,例如
SELECT
A.Agent,
GROUP_CONCAT(T.Name) as Type
FROM Agent AS A
INNER JOIN Type AS T ON T.Type=A.Type
GROUP BY A.Agent
在当前状态下,您可以使用REPLACE代替连接:
SELECT
Agent
,REPLACE(REPLACE(REPLACE(REPLACE(type,'1','Gold'),'2','Platinum'),'3','Silver'),'4','Supreme') as Type
FROM Agent