1

我有以下问题:我尝试选择用户所做的所有投票并将它们放在一列中。我用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 ORDER BY 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,再见?

4

1 回答 1

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
于 2014-07-26T14:53:56.220 回答