假设我们有以下Mysql表:
用户:
userID | user_name
分类:
classificationID | classification_name | classification_ponder
用户分类:
userId(PK) | classificationId(PK)
这是用户和classifiaction之间的n:n关系。
我感兴趣的是如何查询每一个用户,所有在一列中思考最多的分类,用
,
分隔?例如,假设我们有ID=1的user1和以下分类:
classificationId | classification_name | classification_ponder
---------------------------------------------------------------
1 class1 5
2 class2 5
3 class3 4
4 class4 2
用户分类表是(用户拥有所有分类):
userId | ClassificationId
---------------------------
1 1
1 2
1 3
1 4
我想得到的是:
userId | user_name | class1, class2
因此,只有最重要的分类名称(在本例中是
class1
和class2
)显示在一列中,用“,”分隔。我使用以下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>
我想要的是只显示最大思考的分类。
最佳答案
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
像这样的东西应该能起到作用(可能会有一些语法错误)