Foreach非唯一行以获取相关密钥

时间:2014-07-15 15:09:00

标签: mysql innodb

enter image description here

可以制作这样的SELECTion吗?仅基于QTZ_USERS UUID我可以" foreach"所有具有GROUP_ID的成员都可以找到具有最高优先级的GROUP_ID?

我该如何处理?

2 个答案:

答案 0 :(得分:1)

主要是使用GROUP BY和聚合函数执行此操作,此处为MAX

SELECT
    m.UUID,
    MAX(g.PRIORITY)
FROM
    memberships m    
INNER JOIN
    groups  g
ON 
    m.GROUP_ID = g.GROUP_ID
GROUP BY
    m.UUID;

如果您需要GROUP_ID,则可以使用子选择

SELECT
    m.UUID,
    g.GROUP_ID
FROM
    memberships m    
INNER JOIN
      groups  g
ON 
    m.group_id = g.group_id
WHERE
    g.priority = (
         SELECT
             MAX(g2.priority)
         FROM
             groups g2
         WHERE
             g.group_id = g2.group_id
         GROUP BY
             g2.group_id
    );

答案 1 :(得分:1)

假设您需要所有表中的详细信息,请将它们连接在一起并连接到子查询以获取每个用户的最新优先级。

类似于以下内容(尽管选择您想要的实际列而不是使用SELECT *)。

SELECT *
FROM QTZ_USERS u
INNER JOIN MEMBERSHIPS m
ON u.UUID = m.UUID
INNER JOIN GROUPS g
ON m.GROUP_ID = g.GROUP_ID
INNER JOIN
( 
    SELECT m.UUID, MAX(g.PRIORITY) AS max_priority
    FROM MEMBERSHIPS m
    INNER JOIN GROUPS g
    ON m.GROUP_ID = g.GROUP_ID
    GROUP BY m.UUID
) sub0
ON m.UUID = sub0.UUID
AND g.PRIORITY = sub0.max_priority