我有以下 SQL:
SELECT points
FROM memberevents AS me
WHERE memberid = memberevents.memberid
ORDER BY id DESC LIMIT 3;
它返回以下内容:
**points**
123
234
146
但我想创建返回如下的 SQL(只有一条记录用“-”连接点):
**points**
123-234-146
可能吗?
尝试GROUP_CONCAT
:
SELECT GROUP_CONCAT (P.points SEPARATOR '-')
FROM (
SELECT points
FROM memberevents AS me
WHERE memberid = memberevents.memberid
ORDER BY id DESC LIMIT 3) P
GROUP BY P.points;
您想要该group_concat()
功能,但以特定方式:
SELECT substring_index(group_concat(points order by id desc separator '-'), '-', 3)
FROM memberevents AS me
WHERE memberid = memberevents.memberid;
该order by
子句模仿您原来的order by
. 使用separator
您想要的分隔符。选择substring_index()
前三个元素,类似于limit 3
.