2014-01-31 8 views
2

두 테이블이 있습니다 postsposts_replies 모든 게시물을 쿼리하고 타임 스탬프 (게시 시간)별로 순서를 지정합니다. 이제 다음을 수행하고 싶습니다. 사용자가 모든 게시물에 대해 회신 할 때마다 해당 게시물을 벽 상단에 놓으려는 것입니다. 그래서 각 게시물의 타임 스탬프는 최대 값을 얻었습니다. 특정 게시물의 답글의 최대 타임 스탬프.일부 값이 null 인 경우 열을 기준으로 쿼리를 정렬하는 방법?

문제는 일부 게시물에 응답이 없으므로이 게시물의 최대 timestamp_of_replies가 NULL이 될 것이므로 알고 싶습니다. null이 아니고 post_timestamp에 의해 timestamp_of_replies가 결과를 정렬 할 수 있습니까? NULL입니다.

내 쿼리 :

SELECT 
    posts.*, 
    u1.id as user_id, 
    u1.avatar, 
    u1.username as poster_username, 
    u2.username as posted_username , 
    posts.timestamp, 
    f1.recent_reply_time 
FROM 
    posts 
INNER JOIN 
    users u1 
    ON posts.poster_id = u1.id 
INNER JOIN 
    users u2 
    ON posts.posted_id = u2.id 
LEFT JOIN (
    SELECT 
     max(timestamp) as recent_reply_time, 
     post_id 
    FROM 
     posts_replies 
    GROUP BY post_id) f1 
    ON f1.post_id = posts.id 
order by 
    f1.recent_reply_time DESC 

참고 : order by f1.recent_reply_time, posts.timestamp DESC은 저를 잘

+0

. 이런 식으로, 당신은 이제까지 널 타임 스탬프를 가지지 않을 것입니다. 그렇지 않으면, 당신은 IF 문장을 사용하여 널을 무시할 수 있습니다. –

답변

1

의 MySQL은 IF() 기능이 결과를주지 않았다 당신은 또한 ORDER BY 절에서 사용할 수 있음 :

ORDER BY IF(column IS NULL, othercolumn, column) 

귀하의 경우 :

ORDER BY IF(f1.recent_reply_time IS NULL, posts.timestamp, f1.recent_reply_time) 
0

SORTING은 선택에 따라 쉽게 읽을 수 있고 관리 할 수 ​​있습니다. 일부는 sortkey을 선택하고 ORDER BY에서 사용하십시오.

나는 null을 처리하기 위해 COALESCE을 사용했습니다.

SELECT posts.*, 
     u1.id as user_id, 
     u1.avatar, 
     u1.username as poster_username, 
     u2.username as posted_username, 
     posts.timestamp, 
     f1.recent_reply_time, 
     COALESCE(f1.recent_reply_time,posts.timestamp) as sortkey 
    FROM posts 
    INNER JOIN users u1 ON posts.poster_id = u1.id 
    INNER JOIN users u2 ON posts.posted_id = u2.id 
    LEFT JOIN (SELECT max(timestamp) as recent_reply_time, post_id FROM posts_replies GROUP BY post_id) f1 ON f1.post_id = posts.id 
    order by sortkey DESC 
0

사용 COALESCE를 합체 적절한 인수를 사용하여, URE는 sortkey이어야 하나 개 NOT NULL 값을 가질 수 있습니다 : 당신은 응답으로 첫 번째 게시물을 고려할 수

SELECT posts.*, u1.id as user_id, u1.avatar, u1.username as poster_username, 
     u2.username as posted_username , posts.timestamp, f1.recent_reply_time 
FROM posts 
    INNER JOIN users u1 ON posts.poster_id = u1.id 
    INNER JOIN users u2 ON posts.posted_id = u2.id 
    LEFT JOIN (SELECT max(timestamp) as recent_reply_time, post_id 
       FROM posts_replies 
       GROUP BY post_id) f1 ON f1.post_id = posts.id 
ORDER BY COALESCE(f1.recent_reply_time,[alternative value (CURDATE())]) DESC 
관련 문제