반응형
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
반응형
'programing' 카테고리의 다른 글
MariaDB 설치: 설치 중에 서비스로 실행 중 선택을 취소했습니다.mariadb를 시작하고 멈추는 올바른 방법은 무엇입니까? (0) | 2022.09.25 |
---|---|
MySQLDB가 실행하는 실제 쿼리를 인쇄하시겠습니까? (0) | 2022.09.25 |
글로벌 플래그가 있는 RegExp에서 잘못된 결과가 나타나는 이유는 무엇입니까? (0) | 2022.09.25 |
CodeIgniter의 액티브레코드가 있는 데이터베이스에 NOW() 삽입 (0) | 2022.09.22 |
phpmyadmin에서 타임아웃을 해결하려면 어떻게 해야 하나요? (0) | 2022.09.22 |