MySQL GROUP BY以及ORDER BY麻烦

时间:2014-10-16 01:05:56

标签: mysql group-by sql-order-by

在这里和其他地方的所有例子我很沮丧我无法得到这个。我正在尝试对以下查询进行GROUP BY和ORDER BY(没有重复)。

SELECT 
    users.*, user_profile_status.*, photos.*, general.*, 
    experience.*, flagged.*, positions.*, users.user_id AS userID, 
    user_profile_status.user_id AS profileID
FROM users
    LEFT OUTER JOIN user_profile_status ON users.user_id = user_profile_status.user_id
    LEFT OUTER JOIN photos ON users.user_id = photos.user_id 
    LEFT OUTER JOIN general ON users.user_id = general.user_id
    LEFT OUTER JOIN experience ON users.user_id = experience.user_id
    LEFT OUTER JOIN flagged ON users.user_id = flagged.user_id
    LEFT OUTER JOIN positions ON users.user_id = positions.user_id
WHERE 
    users.admin_level = 0

我使用ORDER BY或GROUP BY获得预期结果,但不是两者都得到。两者都返回0行,不应该是这种情况。以下内容返回所有预期的行60 +。

SELECT 
    users.*, user_profile_status.*, photos.*, general.*, 
    experience.*, flagged.*, positions.*, users.user_id AS userID, 
    user_profile_status.user_id AS profileID
FROM users
    LEFT OUTER JOIN user_profile_status ON users.user_id = user_profile_status.user_id
    LEFT OUTER JOIN photos ON users.user_id = photos.user_id 
    LEFT OUTER JOIN general ON users.user_id = general.user_id
    LEFT OUTER JOIN experience ON users.user_id = experience.user_id
    LEFT OUTER JOIN flagged ON users.user_id = flagged.user_id
    LEFT OUTER JOIN positions ON users.user_id = positions.user_id
WHERE 
    users.admin_level = 0
    GROUP BY user_profile_status.user_id 

当我将ORDER BY添加到结尾时,返回0行。

    ORDER BY users.last_login DESC

小提琴:http://sqlfiddle.com/#!2/10dea/8/0

1 个答案:

答案 0 :(得分:0)

显然我在GROUP BY之前放置了ORDER BY - 我在我的问题中说错了。这导致了错误。以下,最后使用ORDER BY。 所以未来要注意自我。 GROUP BY之后的ORDER BY。

SELECT 
    users.*, user_profile_status.*, photos.*, general.*, 
    experience.*, flagged.*, positions.*, users.user_id AS userID, 
    user_profile_status.user_id AS profileID
FROM users
    LEFT OUTER JOIN user_profile_status ON users.user_id = user_profile_status.user_id
    LEFT OUTER JOIN photos ON users.user_id = photos.user_id 
    LEFT OUTER JOIN general ON users.user_id = general.user_id
    LEFT OUTER JOIN experience ON users.user_id = experience.user_id
    LEFT OUTER JOIN flagged ON users.user_id = flagged.user_id
    LEFT OUTER JOIN positions ON users.user_id = positions.user_id
WHERE 
    users.admin_level = 0
    GROUP BY user_profile_status.user_id 
    ORDER BY users.last_login DESC