我对SQL查找没有任何附件的所有帖子的方式感到好奇。
方法#1-子查询NOT IN
这是我第一次尝试构造这样的查询:
global $wpdb;
$sql = "
SELECT p1.ID, p1.post_title
FROM {$wpdb->posts} p1
WHERE p1.post_type = \'post\'
AND p1.post_status = \'publish\'
AND p1.ID NOT IN (
SELECT DISTINCT p2.post_parent
FROM {$wpdb->posts} p2
WHERE p2.post_type = \'attachment\' AND p2.post_parent > 0
)
ORDER BY p1.post_date DESC
";
// Fetch posts without attachments:
$posts_without_attachments = $wpdb->get_results( $sql );
// Display posts without attachments:
foreach( $posts_without_attachments as $post )
{
echo $post->post_title . \'<br/>\';
}
这恰好与@toscho的查询非常相似,但在语法上没有那么精简;-)
方法#2-LEFT JOIN
具有IS NULL
此查询似乎也能正常工作:
global $wpdb;
$sql = "
SELECT p1.ID, p1.post_title
FROM {$wpdb->posts} p1
LEFT JOIN {$wpdb->posts} p2
ON ( p2.post_parent = p1.ID AND p2.post_type = \'attachment\' )
WHERE p1.post_type = \'post\'
AND p1.post_status = \'publish\'
AND p2.post_parent IS NULL
ORDER BY p1.post_date DESC
";
// Fetch posts without attachments:
$posts_without_attachments = $wpdb->get_results( $sql );
在这里,我们将posts表与其自身连接起来,然后选择
NULL
“附件”父列中的行。
方法#3-WP\\u查询posts\\u其中filter aka Method#1
我们还可以修改
WP_Query()
使用
posts_where
过滤器:
// Filter all posts without attachments:
add_filter( \'posts_where\', \'wpse_no_attachments\' );
// Query:
$q = new WP_Query( array( \'post_type\' => \'post\', \'posts_per_page\' => -1 ) );
// Remove the filter:
remove_filter( \'posts_where\', \'wpse_no_attachments\' );
其中:
function wpse_no_attachments( $where )
{
global $wpdb;
$where .= " AND {$wpdb->posts}.ID NOT IN (
SELECT DISTINCT wpse.post_parent
FROM {$wpdb->posts} wpse
WHERE wpse.post_type = \'attachment\' AND wpse.post_parent > 0 ) ";
return $where;
}