2015-01-01 6 views
1

쿼리 결과를 정렬하여 가장 최근 날짜의 행이 결과 집합의 첫 번째 항목이되도록했습니다. 또한 쿼리를 사용하여 모든 conversation_id을 그룹화해야합니다. 그것은하지 않습니다 올바르게 정렬MySQL을 날짜순으로 정렬 한 다음 ID로 정렬하십시오.

SELECT conv.conversation_id, conv.user_id, conv.contact_id, msg.message_id, msg.message, msg.sent_date 
FROM (SELECT * FROM message ORDER BY sent_date DESC) as msg 
LEFT JOIN conversation AS conv 
ON conv.contact_id = msg.contact_id 
WHERE user_id = 24 
ORDER BY conversation_id; 

:

여기에 내 현재 쿼리입니다. http://imgur.com/QLoEj6H

내가 필요하면 상단에 될 conversation_id 2 그룹입니다 :

나는 위의 쿼리를 사용하여이 테이블을 얻을. 쿼리의 마지막에있는 ORDER BYDESC으로 변경하면 테이블의 모든 값에 대해 작동하지 않습니다.

+0

.... 주문 ID로 오름차순으로 오름차순? – IceJOKER

답변

0

친구와 Gordon Linoff의 대답을 통해 알아 냈습니다. 다음은 작동 할 코드입니다.

SELECT conv.conversation_id, conv.user_id, conv.contact_id, 
     msg.message_id, msg.message, msg.sent_date 
FROM message msg LEFT JOIN 
    conversation conv 
    ON conv.contact_id = msg.contact_id LEFT JOIN 
    (SELECT conversation_id, MAX(sent_date) as max_msg_sent_date 
     FROM message 
     GROUP BY conversation_id 
    ) mmax 
    ON mmax.conversation_id = msg.conversation_id 
WHERE user_id = 24 
ORDER BY max_msg_sent_date desc, msg.conversation_id, msg.sent_date DESC; 
1

하위 쿼리는 쿼리 속도를 늦추는 것 외에는 아무 작업도 수행하지 않습니다.

대화로 주문한 것이 가장 최근 대화로 먼저 나와야하는 것 같습니다. 그래서, 당신은 추가 join 사용하여 쿼리에 그 정보를 가지고해야하는 경우 :

SELECT conv.conversation_id, conv.user_id, conv.contact_id, 
     msg.message_id, msg.message, msg.sent_date 
FROM message msg LEFT JOIN 
    conversation conv 
    ON conv.contact_id = msg.contact_id LEFT JOIN 
    (SELECT conversation_id, MAX(sent_date) as max_ent_date 
     FROM message 
     GROUP BY conversation_id 
    ) mmax 
    ON mmax.conversation_id = m.conversation_id 
WHERE user_id = 24 
ORDER BY mmax.max_sent_date desc, m.conversation_id; 
+0

그건 작동하지 않습니다. 그것은 내게 이것을 준다 : http://imgur.com/7r0uofT – kennyjwilli

+0

@kennyjwilli. . . 그건 말이되지 않습니다. 'conversation_id = 2 '를 가진 모든 것은'join' 때문에'max_msg_sent_date'와 같아야합니다. 동일한 대화의 메시지가 함께 있어야합니다. SQL Piddle을 설정해야합니다. –

+0

실은 당신이 대답을 업데이 트 기다려 .. 난 '알 수없는 열'msg_sent_date '필드 목록에서'얻을. 해당 쿼리에서 아무 것도 가리 키지 않는 여러 이름이있는 것 같습니다. – kennyjwilli

0

는 서브 쿼리없이 ORDER BY conversation_id DESC, sent_date DESC를 사용해보십시오.

이렇게하면 conversation_id가 감소하는 순서로 결과가 검색되고, 관련성이있는 경우 결과가 내림차순으로 정렬됩니다. (그것이 당신이 찾고있는 것이라면)

+0

이것도 작동하지 않습니다 : http://imgur.com/yaHxdbW 2015-01-02 – kennyjwilli

+0

의 최신 메시지를 가지고 있기 때문에'conversation_id' = 2가있는 "group"이 맨 위에 있어야합니다. 내 대답이 업데이트되었습니다. – shikharsaxena30

+0

'GROUP BY'문제는 각 coversation_id에 대해 1 개의 결과가 아닌 모든 결과가 필요합니다. – kennyjwilli

관련 문제