MySql通过不显示正确的结果来排序

时间:2015-12-24 09:55:17

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

我有3个表项目,讨论&评论。项目有多个讨论,每个讨论都有多个评论。

我想将最后一次讨论添加到讨论表中,但没有评论。我还需要与特定讨论相关联的项目详细信息。

我的查询如下:
SELECT 
    p.PRO_Id, p.PRO_Name,
    d.DIS_ThreadDesc, dev.DEV_Name, loc.LOC_Name, d.USE_Id, d.DIS_Date
FROM projects p LEFT JOIN discussions d ON p.PRO_Id = d.PRO_Id LEFT JOIN developer dev ON p.DEV_Id=dev.DEV_Id LEFT JOIN locality loc ON p.LOC_Id=loc.LOC_Id WHERE p.PRO_Status=1 and d.DIS_Status=1 AND d.DIS_Id NOT IN ( select DIS_Id from comments where COM_Status=2 ) GROUP BY p.PRO_Id ORDER BY d.DIS_Id desc LIMIT 3
我通过降序排序讨论表(ORDER BY d .DIS_Id)但仍然需要第一条记录而不是最后一条记录。我在这里做错了什么?

1 个答案:

答案 0 :(得分:2)

试试这个:

SELECT p.PRO_Id, p.PRO_Name, d.DIS_ThreadDesc, dev.DEV_Name, 
       loc.LOC_Name, d.USE_Id, d.DIS_Date
FROM projects p
INNER JOIN discussions d ON p.PRO_Id = d.PRO_Id 
INNER JOIN (SELECT d.PRO_Id, MAX(d.DIS_Id) lastDisc 
            FROM discussions d  
            WHERE d.DIS_Status = 1 
            GROUP BY d.PRO_Id
          ) AS A ON d.PRO_Id = A.PRO_Id AND d.DIS_Id = A.lastDisc 
LEFT OUTER JOIN comments c ON d.DIS_Id = c.DIS_Id AND c.COM_Status=2 
LEFT OUTER JOIN developer dev ON p.DEV_Id = dev.DEV_Id 
LEFT OUTER JOIN locality loc ON p.LOC_Id = loc.LOC_Id
WHERE p.PRO_Status = 1 AND c.DIS_Id IS NULL
ORDER BY d.DIS_Id DESC;