我的wordpress数据库上的mysql查询有问题。
我有国家和城市的自定义字段。
目前,我有一个显示“英国”国家所有城市的查询
$querystr = "
SELECT wposts.*
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE wposts.ID = wpostmeta.post_id
AND wpostmeta.meta_key = \'Country\'
AND wpostmeta.meta_value = \'UK\'
AND wposts.post_type = \'post\'
ORDER BY wpostmeta.meta_value DESC
";
$pageposts = $wpdb->get_results($querystr, OBJECT);
这是php foreach的查询,显示所有城市
<?php
$querystr = "
SELECT wposts.*
FROM $wpdb->posts wposts, $wpdb->postmeta wpostmeta
WHERE wposts.ID = wpostmeta.post_id
AND wpostmeta.meta_key = \'Country\'
AND wpostmeta.meta_value = \'UK\'
AND wposts.post_type = \'post\'
";
$pageposts = $wpdb->get_results($querystr, OBJECT);
?>
<?php if ($pageposts): ?>
<?php global $post; ?>
<?php foreach ($pageposts as $post): ?>
<?php setup_postdata($post); ?>
<?php echo get_post_meta($post->ID, \'city\', true) ?> <br />
<?php endforeach; ?>
<?php endif; ?>
这个查询列出了所有英国城市从我的WordPress自定义字段“城市”中获取的数据。
此查询返回城市列表,如:
Aberdeen
Aberdeen
Aberdeen
Aberdeen
Aberdeen
Belfast
Belfast
Belfast
Belfast
Belfast
Birchington
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Birmingham
Blackpool
Bournemouth
Bournemouth
Bournemouth
Bournemouth
Bournemouth
Bournemouth
Bournemouth
Bournemouth
Brighton
Brighton
等等。!!!
正如您所看到的,“city”字段值重复,我需要显示一次城市并获得如下列表
Aberdeen
Belfast
Birchington
Birmingham
Blackpool
Bournemouth
Brighton
Bristol
我怎样才能得到这个?谢谢大家!!
最合适的回答,由SO网友:TheDeadMedic 整理而成
这里不需要自定义SQL,请使用元查询的强大功能:
$posts = get_posts(
array(
\'posts_per_page\' => -1,
\'meta_query\' => array(
array(
\'key\' => \'Country\',
\'value\' => \'UK\',
),
),
)
);
foreach ( $posts as $post )
$cities[] = get_post_meta( $post->ID, \'city\', true );
foreach ( array_unique( $cities ) as $city )
echo $city . \'<br />\';