如何将以下3个表格SQL查询翻译成Grails?
SELECT t.name, count(*) as c
FROM topic t
LEFT OUTER JOIN article_topics at
ON t.id = at.topic_id
LEFT OUTER JOIN article a
ON at.article_id = a.id
GROUP BY t.name
我一直在尝试类似但不确定如何进行连接
def criteria = Topic.createCriteria()
criteria.list {
groupProperty("name")
projections {
count('*')
}
}
或者如果我尝试使用
,它可能更好/更容易Topic.executeQuery(..insert sql..)
如果它有帮助,我有文章和主题GORM对象和文章
static mapping = {
topics lazy: false, joinTable: [name: 'article_topics', column: 'topic_id', key: 'article_id']
}
答案 0 :(得分:0)
托德。在grails中,您可以使用hbernate本机sql查询,如hr hacki在此post中所述。
我分享了一个从生产代码中获取的示例,该代码使用了该出版物中描述的技术并使用了左连接。
List<Map<String, Object>> resumeInMonth(final String monthName) {
final session = sessionFactory.currentSession
final String query = """
SELECT
t.id AS id,
e.full_name AS fullName,
t.subject AS issue,
CASE t.status
WHEN 'open' THEN 'open'
WHEN 'pending' THEN 'In progress'
WHEN 'closed' THEN 'closed'
END AS status,
CASE t.scheduled
WHEN TRUE THEN 'scheduled'
WHEN FALSE THEN 'non-scheduled'
END AS scheduled,
ifnull(d.name, '') AS device,
DATE(t.date_created) AS dateCreated,
DATE(t.last_updated) AS lastUpdated,
IFNULL(total_tasks, 0) AS tasks
FROM
tickets t
INNER JOIN
employees e ON t.employee_id = e.id
LEFT JOIN
devices d ON d.id = t.device_id
LEFT JOIN
(SELECT
ticket_id, COUNT(1) AS total_tasks
FROM
tasks
GROUP BY ticket_id) ta ON t.id = ta.ticket_id
WHERE
MONTHNAME(t.date_created) = :monthName
ORDER BY dateCreated DESC
"""
final sqlQuery = session.createSQLQuery(query)
final results = sqlQuery.with {
resultTransformer = AliasToEntityMapResultTransformer.INSTANCE
setString('monthName', monthName)
list()
}
results
}
我希望它对你有用