[英]MYSQL - GROUP_CONCAT AND FIND_IN_SET are mixing values/order?
I have the following problem: I try to select all the votes a user made and put them out in one column. 我遇到以下问题:我尝试选择用户进行的所有投票,然后将它们放在一栏中。 I use GROUP_CONCAT
for this, but somehow it is mixing the values order. 我为此使用GROUP_CONCAT
,但是不知何故它在混合值顺序。
This is the SQL code: 这是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 ORDER BY user_login.class GROUP BY user_login.id ORDER BY user_login.class
An example value for votes would be: 投票的示例值是:
id | event_id | question_id | selected | user_id
25 14 42 52,46,41 1
26 14 43 68 1
Options is like: 选项如下:
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
Questions is like: 问题就像:
id | question_name | event_id
42 Project Number 14
43 Greeting 14
Event is like: 事件就像:
id | title
14 Project Testing
And the output of the given code is: 给定代码的输出为:
selected | event_title
Project C, Bye, ProjectD, Project B Test
How can I keep the original order, so that it outputs me: Project D, Project C, Project B, Bye? 如何保持原始订单,以便输出我的订单:Project D,Project C,Project B,Bye?
would something like this work? 这样的事情会工作吗? basically you say order by the field values and make them look like '52','46',... etc. 基本上,您说的是按字段值排序,并使它们看起来像“ 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
EDIT: 编辑:
my preferred way to do this is to make a variable that has the string.. its easier to read and you can ensure it does the correct order this way.. 我这样做的首选方法是使具有字符串的变量易于读取,并且可以确保以这种方式执行正确的顺序。
SET @order_field := (
SELECT
group_concat(
CONCAT('"', replace(selected, ',', '","'), '"')
)
FROM votes);
then the query would be a lot easier to read... 那么查询将更容易阅读...
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.