gpt4 book ai didi

另一个 GROUP_CONCAT 中的 MySQL GROUP_CONCAT

转载 作者:行者123 更新时间:2023-11-29 05:04:29 25 4
gpt4 key购买 nike

有可能吗?我想要得到的是这样的:

+-------------------------------+
| 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

并得到错误“Invalid use of group function”,这真是黑幕-_-由于复杂的查询(较低),我按分组方式进行分组。

我做错了什么或者仅在 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

最佳答案

你应该使用 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

关于另一个 GROUP_CONCAT 中的 MySQL GROUP_CONCAT,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51234627/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com