2017-10-03 5 views
2

2つの列を合計する基本的な操作に問題があります。シンプルですが動作しません。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; 

そして、これが結果です:

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 
関連する問題