2017-10-03 1 views
2

두 개의 열을 합산하는 기본 작업에 문제가 있습니다. 간단하지만 작동하지 않습니다.SQL 추가 열

내가 얻을 결과 5 + = 8 5 + 7 = 7

이 3 쿼리입니다 :

select 
    `wp_posts`.ID , 
    (select count(*) from `co_likes` 
    where `wp_posts`.`ID` = `co_likes`.`id_post` 
     and `co_likes`.`deleted_at` is null) as `like_count`, 
    (select count(*) from `wp_comments` 
    where `wp_posts`.`ID` = `wp_comments`.`comment_post_ID`) as `comment_count` , 
    (`comment_count`+`like_count`) as 'total_sum' 
from 
    `wp_posts` 
where 
    `post_type` in ('post', 'co_post') 
    and `post_status` = 'publish' 
order by 
    (comment_count+like_count) desc; 

그리고 이것은 결과입니다

enter image description here

있어 무슨 일이 일어나고 있는지 생각해?

+0

같은 쿼리에서 이전에 정의 된 열 별칭을 사용할 수 없습니다.이 쿼리가 처음 실행 된 방식이 확실하지 않습니다. –

답변

2

열 별칭은 정의 된대로 select (또는 where)에서 사용할 수 없습니다.

select p.*, (`comment_count`+`like_count`) as total_sum 
from (select `wp_posts`.ID , 
      (select count(*) from `co_likes` where `wp_posts`.`ID` = `co_likes`.`id_post` and `co_likes`.`deleted_at` is null) as `like_count`, 
      (select count(*) from `wp_comments` where `wp_posts`.`ID` = `wp_comments`.`comment_post_ID`) as `comment_count` , 
     from `wp_posts` 
     where `post_type` in ('post', 'co_post') and `post_status` = 'publish' 
    ) p 
order by total_sum desc; 

만 합으로 주문하고 싶지만, 그것을 볼 필요가없는 경우, 당신은 order by의 합계를 넣을 수 있습니다 :

귀하의 경우, 최선의 최선은 아마도 하위 쿼리입니다
 select `wp_posts`.ID , 
      (select count(*) from `co_likes` where `wp_posts`.`ID` = `co_likes`.`id_post` and `co_likes`.`deleted_at` is null) as `like_count`, 
      (select count(*) from `wp_comments` where `wp_posts`.`ID` = `wp_comments`.`comment_post_ID`) as `comment_count` , 
     from `wp_posts` 
     where `post_type` in ('post', 'co_post') and `post_status` = 'publish' 
     order by (like_count + comment_count) desc