使用多个JOINS

时间:2017-07-07 15:34:54

标签: mysql sql grails hql gorm

大家。

我使用grails 3.3.0.M2框架,mysql作为数据源,以下sql查询按预期工作

SELECT 
    c.name,
    SUM(CASE
        WHEN t.status = 'open' THEN 1
        ELSE 0
    END) 'open',
    SUM(CASE
        WHEN t.status = 'pending' THEN 1
        ELSE 0
    END) 'in progress',
    SUM(CASE
        WHEN t.status = 'closed' THEN 1
        ELSE 0
    END) 'closed'
FROM
    tickets t
        INNER JOIN
    users u ON t.user_id = u.id
        INNER JOIN
    user_coordinations uc ON uc.user_id = u.id
        INNER JOIN
    coordinations c ON c.id = uc.coordination_id
GROUP BY 1

我使用隐式JOIN 转换为HQL但是我得到了错误的结果,这里是hql查询:

SELECT 
    c.name,
    SUM(CASE
        WHEN t.status = 'open' THEN 1
        ELSE 0
    END),
    SUM(CASE
        WHEN t.status = 'pending' THEN 1
        ELSE 0
    END),
    SUM(CASE
        WHEN t.status = 'closed' THEN 1
        ELSE 0
    END)
FROM
    Ticket t, User u, UserCoordination uc, Coordination c
WHERE
    MONTH(t.dateCreated) = :month
GROUP BY 1

为了获得正确的结果,堆栈溢出用户帮助我理解查询需要使用显式JOINS,这里的问题是:Group by a field that does not belongs to the consulted table

现在我正在尝试使用以下查询:

SELECT 
    c.name,
    SUM(CASE
        WHEN t.status = 'open' THEN 1
        ELSE 0
    END),
    SUM(CASE
        WHEN t.status = 'pending' THEN 1
        ELSE 0
    END),
    SUM(CASE
        WHEN t.status = 'closed' THEN 1
        ELSE 0
    END)
FROM
    Ticket t
        INNER JOIN
    User u
        INNER JOIN
    UserCoordination uc
        INNER JOIN
    Coordination c
WHERE
    MONTH(t.dateCreated) = :month
GROUP BY 1

但是我收到了一条 com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException 并显示了导致的消息您的SQL语法中有错误;检查与您的MySQL服务器版本相对应的手册,以便在第1行的“内部联接用户协调协调”下使用“内部联接user_coordinations usercoordi2_”附近使用正确的语法

感谢您的帮助和时间

1 个答案:

答案 0 :(得分:0)

SELECT new map(
    c.name as name,
(CASE
        WHEN t.status = 'open' THEN 1
        ELSE 0
    END) as open,
(CASE
        WHEN t.status = 'pending' THEN 1
        ELSE 0
    END) as pending, 
(CASE
        WHEN t.status = 'closed' THEN 1
        ELSE 0
    END) as closed,
    SUM(open) as openSum,
    SUM(pending) as pendingSum,
    SUM(closed) as closedSum
)
FROM
    Ticket t
        left join t.user u left join u.userCoordination uc left join uc.coordination c 
WHERE
    MONTH(t.dateCreated) = :month

// GROUP BY 1

上面缺少的东西更像是你需要的东西 select new map(i.item as item...如果您将此基本知识与您所拥有的内容以及我尝试做的事情进行比较,您就会明白为什么会出现错误。

不确定你的小组应该是分组的。如果你只是意味着一个连接,那么我不确定是否是一个连接,如果是这种情况,请忽略所有左连接,因为左连接尝试连接并获得任何null hasMany关系等。