我正在将一系列查询从MySQL转换为PostgreSQL,以在特定的Moodle实例上运行。无论如何我都不是这两种语言的专家,这使我感到非常复杂,为什么PostgreSQL在我的GROUP BY子句上抛出语法错误。如何正确创建GROUP BY子句?
我在StackOverflow上查看了其他答案,其中提到GROUP BY子句要求列出SELECT语句中的所有列。我已将其他列添加到GROUP BY子句(请参见下面的注释掉的代码)。但是,同样的问题仍然存在。
它在Moodle应用程序(此处的数据库结构:https://moodleschema.zoola.io/index.html)上的SQL报告工具中运行。
-- valid MySQL query. This query selects the course name, counts the times the course has been accessed within the last 12 months and displays it in a table IF it is a visible course.
SELECT c.fullname, count(course) AS actions, course AS courseid, c.visible AS visibility
FROM prefix_log l, prefix_course c
WHERE l.course = c.id
AND c.visible = 1
AND time BETWEEN unix_timestamp(date_sub(Now(), INTERVAL 12 MONTH)) AND unix_timestamp(Now())
AND c.id != 1
GROUP BY course
ORDER BY actions DESC
--postgreSQL conversion attempt
SELECT c.fullname, count(course) AS actions, course AS courseid, c.visible AS visibility
FROM prefix_log l, prefix_course c
WHERE l.course = c.id
AND c.visible = 1
AND extract(epoch from NOW()) BETWEEN extract(epoch from NOW()- INTERVAL '12 months') AND to_date(NOW()::TEXT
AND c.id != 1
GROUP BY course
-- Query failed
--
-- ERROR: syntax error at or near "GROUP"
-- LINE 7: GROUP BY course
-- ^
-- When using the 'GROUP BY course, actions, c.fullname, c.visible' clause:
-- Query failed
--
-- ERROR: syntax error at or near "GROUP"
-- LINE 8: GROUP BY course, actions, c.fullname, c.visible
-- ^
ORDER BY actions DESC
我希望从MySQL到PostgreSQL的转换尝试是有效的,并且会返回过去12个月内活动课程的列表,但是我无法验证转换尝试。
编辑:解决方案 @Jeremy指出,我在WHERE语句的12个月子句中缺少右括号。我还修复了代码中的一些结果性小错误-参见下文。
SELECT c.fullname as CourseName, COUNT(course) AS actions, course AS courseid, c.visible AS visibility
FROM prefix_log l, prefix_course c
WHERE l.course = c.id
AND c.visible = 1
AND extract(epoch from NOW()) BETWEEN extract(epoch from NOW()- INTERVAL '12 months') AND extract(epoch from NOW())
AND c.id != 1
GROUP BY course, c.fullname, c.visible
ORDER BY actions DESC
答案 0 :(得分:0)
此行缺少右括号:
AND extract(epoch from NOW()) BETWEEN extract(epoch from NOW()- INTERVAL '12 months') AND to_date(NOW()::TEXT
这也没有任何意义,但是语法错误是由于缺少右括号引起的。
现在将永远是现在到十二个月前。现在将文本转换为日期并将其转换为日期最多不过是一个额外的步骤,但是在此之后您显然会缺少部分逻辑。