SQL计数但排除某些行

时间:2017-02-24 13:45:10

标签: mysql

我正在运行一个计算提交帖子的查询:

SELECT COUNT(*) 
FROM `wp_posts` 
WHERE `post_author` = 4 
  AND `post_type` = 'nf_sub' 
  AND `post_status` = 'publish'

这将返回所有帖子。现在我想排除_form_id_ = 1的帖子。此查询:

SELECT * 
FROM `wp_postmeta` 
WHERE `post_id` = 225 
  AND `meta_key` = '_form_id' 
  AND `meta_value` = 1

如何将两者合并为一个只计算_form_id_不等于1的行的查询?

2 个答案:

答案 0 :(得分:0)

从表中,假设链接字段是wp_posts表中的主键wpposts_id

使用以下内部查询,还有其他方法可以实现此目的。

SELECT COUNT(*) 
FROM `wp_posts` 
WHERE `post_author` = 4 
  AND `post_type` = 'nf_sub' 
  AND `post_status` = 'publish' 
  and  `wppost_id` not in ( SELECT  `wppost_id` 
                            from `wp_postmeta` 
                            WHERE `post_id` = 225 
                              AND `meta_key` = '_form_id' 
                              AND `meta_value` = 1
                          );

答案 1 :(得分:0)

这就是答案。感谢所有提供线索的人。

SELECT COUNT(*) FROM `wp_posts` WHERE `post_author` = ".get_current_user_id()." AND `post_type` = 'nf_sub' AND `post_status` = 'publish' AND `ID` NOT IN ( SELECT `post_id` FROM `wp_postmeta` WHERE `meta_key` = '_form_id' AND `meta_value` = 1)