Mysql仅从n:n关系中检索特定值

时间:2012-01-07 12:26:33

标签: mysql

假设我们有以下Mysql表:

用户:

userID | user_name

分类

classificationID | classification_name | classification_ponder

user_classification:

userId(PK) | classificationId(PK)

这是用户和分类之间的n:n关系。

我感兴趣的是如何查询每个用户,在一列中使用最大值思考的所有分类,用, 分隔?

E.g。假设我们有ID = 1的user1和以下分类:

 classificationId | classification_name | classification_ponder
---------------------------------------------------------------
        1                 class1                     5 
        2                 class2                     5 
        3                 class3                     4
        4                 class4                     2

user_classification表是(用户拥有所有分类):

 userId | ClassificationId
---------------------------
    1            1
    1            2
    1            3
    1            4

我想得到的是:

userId | user_name | class1, class2

因此,只有具有最大思考的分类名称(在这种情况下为class1class2)显示在一列中,以“,”分隔。

我成功通过以下mysql查询获取用户的所有分类:

select 
  user.user_name,
  GROUP_CONCAT(DISTINCT Classification.classification_name) as Classification 
from user 
left join user_classification 
  on (user_classification.userId=user.userID) 
left join Classification 
  on (Classification.classificationID=user_classification.classificationId) 
GROUP BY user.userID</b>

我想要的是只显示最大思考的分类。

1 个答案:

答案 0 :(得分:0)

SELECT 
    u.user_name,
    GROUP_CONCAT(DISTINCT c.classification_name) as Classification
FROM `user` u
INNER JOIN 
(
    SELECT 
        user_classification.userId as uid,
        MAX(classification.classification_ponder as max_ponder
    FROM user_classification
    INNER JOIN classification ON user_classification.classificationId = classification.classificationID
    GROUP BY user_classification.userId
) as user_max ON u.userID = user_max.uid
LEFT JOIN user_classification uc ON u.userID = uc.userId
LEFT JOIN classification c ON uc.classificationId = c.classificationID AND user_max.max_ponder = c.classification_ponder
GROUP BY u.userID

这样的事情应该可以解决问题(可能有一些语法错误)