2014-07-15 59 views

回答

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 
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 
    );