我遇到以下问题:我尝试选择用户所做的所有投票并将其放在一列中。我为此使用GROUP_CONCAT
,但不知何故它混合了值的顺序。
这是SQL代码:
SELECT
GROUP_CONCAT(DISTINCT options.option_name SEPARATOR ',') AS selected,
user_login.firstname, user_login.lastname,
event.event_title
FROM
options, user_login, event, votes, questions
WHERE
event.id = ? AND questions.Event_id = event.id
AND votes.user_id = user_login.id AND votes.question_id = questions.id
AND FIND_IN_SET(options.id, selected)
GROUP BY user_login.id 订购 user_login.class
投票的示例值是:
id | event_id | question_id | selected | user_id
25 14 42 52,46,41 1
26 14 43 68 1
选项如:
id | option_name | question_id
40 Project A 42
41 Project B 42
46 Project C 42
52 Project D 42
67 Hello 43
68 Bye 43
问题就像:
id | question_name | event_id
42 Project Number 14
43 Greeting 14
事件就像:
id | title
14 Project Testing
给定代码的输出是:
selected | event_title
Project C, Bye, ProjectD, Project B Test
如何保留原始订单,以便输出我: 项目D,项目C,项目B,再见?
答案 0 :(得分:1)
会是这样的吗?基本上你说字段值的顺序,使它们看起来像'52','46',......等等。
SELECT
GROUP_CONCAT(DISTINCT options.option_name
ORDER BY FIELD( options.id,
concat('"',
replace(selected, ',', '","'),
'"')
)
SEPARATOR ','
) AS selected,
user_login.firstname, user_login.lastname,
event.event_title
FROM options, user_login, event, votes, questions
WHERE event.id = ? AND questions.Event_id = event.id
AND votes.user_id = user_login.id AND votes.question_id = questions.id
AND FIND_IN_SET(options.id, selected)
GROUP BY user_login.id
ORDER BY user_login.class
修改强>
我这样做的首选方法是创建一个包含字符串的变量..它更容易阅读,你可以确保它以这种方式执行正确的顺序..
SET @order_field := (
SELECT
group_concat(
CONCAT('"', replace(selected, ',', '","'), '"')
)
FROM votes);
然后查询会更容易阅读...
SELECT
GROUP_CONCAT(DISTINCT options.option_name
ORDER BY FIELD( options.id, @order_field)
SEPARATOR ','
) AS selected,
user_login.firstname, user_login.lastname,
event.event_title
FROM options, user_login, event, votes, questions
WHERE event.id = ? AND questions.Event_id = event.id
AND votes.user_id = user_login.id AND votes.question_id = questions.id
AND FIND_IN_SET(options.id, selected)
GROUP BY user_login.id
ORDER BY user_login.class