我想从MySQL表中检索数据并将其格式化为“Bruno,Phil Sturgeon和Simon”。具体来说,我想用逗号连接所有值,除了最后一个,我想用“和”连接。
现在我只能用逗号连接所有值。如何用“和”代替最后一个实例?
这是我的问题:
SELECT
b.title,
GROUP_CONCAT(a.name ORDER BY name SEPARATOR ',') AS name
FROM `book` AS b
LEFT JOIN `book_authors` AS ba
ON b.id = ba.book_id
INNER JOIN `author` AS a
ON a.id = ba.author_id
GROUP BY b.id
ORDER BY b.title
答案 0 :(得分:1)
取值到最后一个逗号,CONCAT为'AND',然后添加最后一个值
SELECT
b.title,
CONCAT(SUBSTRING_INDEX( GROUP_CONCAT(a.name ORDER BY name SEPARATOR ','),',',length( GROUP_CONCAT(a.name ORDER BY name SEPARATOR ','))-length(replace( GROUP_CONCAT(a.name ORDER BY name SEPARATOR ','),',',''))),
' AND ',SUBSTRING_INDEX( GROUP_CONCAT(a.name ORDER BY name SEPARATOR ','),',',-1)) AS name
FROM `book` AS b
LEFT JOIN `book_authors` AS ba
ON b.id = ba.book_id
INNER JOIN `author` AS a
ON a.id = ba.author_id
GROUP BY b.id
ORDER BY b.title
Here它是硬编码的
答案 1 :(得分:0)
“用户定义变量”,CONCAT
和SUBSTRING_INDEX
功能的优化解决方案。
这将立即调用GROUP_CONCAT
,并且仅使用变量@name
执行进一步的操作:
SET @name = "";
SELECT CONCAT(LEFT(@name, LENGTH(@name) - LENGTH(SUBSTRING_INDEX(@name,',',-1))-1), ' and ', SUBSTRING_INDEX(@name, ',', -1)) name, title
FROM
(SELECT
b.title as title,
@name:= GROUP_CONCAT(a.name ORDER BY name SEPARATOR ',') AS name
FROM `book` AS b
LEFT JOIN `book_authors` AS ba
ON b.id = ba.book_id
INNER JOIN `author` AS a
ON a.id = ba.author_id
GROUP BY b.id
ORDER BY b.title) as t;