有可能吗? 我想得到的是这样的:
+-------------------------------+
| data 1 (another1, another2); |
| data 2 (another1 ..... ) |
+-------------------------------+
在表格中显示以下内容:
--------------------------------+
data1 | another1 | foreign key1 |
--------------------------------+
data1 | another2 | foreign key1 |
--------------------------------+
data2 | another1 | foreign key1 |
--------------------------------+
我使用此代码
GROUP_CONCAT(DISTINCT CONCAT(data, ' (', another, ')') SEPARATOR ';\r\n ') as InOneCell
并获得以下输出:
+-------------------------------+
| data 1 (another1); |
| data 1 (another2); |
| data 2 (another1); ... |
+-------------------------------+
尝试过:
GROUP_CONCAT(DISTINCT CONCAT(data, ' (', GROUP_CONCAT(another SEPARATOR ', '), ')') SEPARATOR ';\r\n ') as InOneCell
并收到错误“无效使用组功能” ,这确实是可疑的-_- 我会按分组进行分组-由于复杂的查询(下图),因此要先显示密钥。
我做错了还是仅在SQL上是不可能的?
完整查询:
SELECT
s.name,
s.surname,
gr.number AS 'group',
s.bitrh_date,
s.email,
s.registration_ip,
s.registration_time,
GROUP_CONCAT(DISTINCT CONCAT(dis.code, ' ', dis.title, ' (', GROUP_CONCAT(DISTINCT g.mark SEPARATOR ', '), ')') SEPARATOR ';\r\n ') as learning,
ROUND(AVG(g.mark), 2) AS average,
gr.semester,
ref.text AS reference
FROM t_students s
LEFT JOIN t_grades g
ON s.id = g.student
LEFT JOIN t_groups gr
ON s.group_id = gr.id
LEFT JOIN t_references ref
ON ref.author = s.id
LEFT JOIN t_program prog
ON gr.id = prog.group_id
LEFT JOIN t_disciplines dis
ON prog.discipline_id = dis.code
GROUP BY s.id
ORDER BY s.registration_time DESC
答案 0 :(得分:2)
我想您可以尝试一下,只使用一次GROUP_CONCAT
,然后添加GROUP BY
SELECT CONCAT(data,'(',GROUP_CONCAT(DISTINCT another),');')
FROM T
group by data
答案 1 :(得分:1)
您应该使用group by(单个group_concat就足够了)
select CONCAT(data, ' (', GROUP_CONCAT(another SEPARATOR ', '), ');') as InOneCell
from my_table
group by data
或者您可以使用子查询
select data, group_concat(my_group)
from (
select data, group_concat(another) my_group
group by data
) t
group by data
在您的情况下 您可以使用子查询,例如:
SELECT
s.name,
s.surname,
gr.number AS 'group',
s.bitrh_date,
s.email,
s.registration_ip,
s.registration_time,
GROUP_CONCAT(DISTINCT CONCAT(dis.code, ' ', dis.title, ' (', t.learning, ')') SEPARATOR ';\r\n ') as learning,
t.average,
gr.semester,
ref.text AS reference
FROM t_students s
LEFT JOIN (SELECT
student,
GROUP_CONCAT(DISTINCT mark SEPARATOR ', ') learning,
ROUND(AVG(mark), 2) AS average
from t_grades
group by student
) t on t.student = s.id
LEFT JOIN t_groups gr
ON s.group_id = gr.id
LEFT JOIN t_references ref
ON ref.author = s.id
LEFT JOIN t_program prog
ON gr.id = prog.group_id
LEFT JOIN t_disciplines dis
ON prog.discipline_id = dis.code
GROUP BY s.id
ORDER BY s.registration_time DESC