programing

SQL 열 추가

copysource 2022. 9. 25. 14:41
반응형

SQL 열 추가

두 열을 합산하는 기본 연산에 문제가 있습니다.그것은 간단하지만 효과가 없다.

결과 5 + 5 = 8, 3 + 7 = 7

다음은 쿼리입니다.

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;

결과는 다음과 같습니다.

여기에 이미지 설명 입력

무슨 일인지 짐작이 가요?

동일한 열 별칭을 사용할 수 없습니다.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

언급URL : https://stackoverflow.com/questions/46546182/sql-adding-columns

반응형