使用GROUP BY和ORDER BY MAX()进入桌面

时间:2016-09-29 11:08:33

标签: mysql

此代码正常运行

SELECT
    c.id_article,
    a.titre AS title_article
FROM comments AS c
LEFT JOIN articles AS a
    ON a.id = c.id_article
WHERE c.hide = 0
GROUP BY c.id_article
ORDER BY MAX(c.date) DESC
LIMIT 0, 6

但我需要文章中最后一条评论的用户名。

我试试这个

SELECT
    c.id_article,
    a.titre AS title_article,
    u.nom_utilisateur AS user_name
FROM comments AS c
LEFT JOIN articles AS a
    ON a.id = c.id_article
LEFT JOIN membres AS u
    ON c.id_user = u.id
WHERE c.hide = 0
GROUP BY c.id_article
ORDER BY MAX(c.date) DESC
LIMIT 0, 6

并且没有工作......

任何帮助?

(抱歉我的英语不好......)

2 个答案:

答案 0 :(得分:0)

如果没有错误消息或描述有什么问题,那么很难说,但无论如何,您在u.nom_utilisateur语句中没有包含GROUP BY

MySQL通常允许这样做而不会抛出错误,但它可能会导致意外结果。

SELECT
    c.id_article,
    a.titre AS title_article,
    u.nom_utilisateur AS user_name
FROM comments AS c
LEFT JOIN articles AS a
    ON a.id = c.id_article
LEFT JOIN membres AS u
    ON c.id_user = u.id
WHERE c.hide = 0
GROUP BY c.id_article, u.nom_utilisateur
ORDER BY MAX(c.date) DESC
LIMIT 0, 6

答案 1 :(得分:0)

我有部分解决方案。

我使用此代码检索文章中的最后一条评论:

nil

在第一次使用SELECT之后,我使用此代码从最后一条评论中检索用户名:

SELECT
    c.id_article,
    MAX(c.id) AS last_id_comment,
    a.titre AS title_article
FROM comments AS c
LEFT JOIN articles AS a
    ON a.id = c.id_article
WHERE c.hide = 0
GROUP BY c.id_article
ORDER BY MAX(c.date) DESC
LIMIT 0, 6

不是最好的解决方案,但它起作用。