2013-06-26 79 views
1

我在我的wordpress數據庫的mysql查詢有問題。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 

等!

,你可以看到有「城市」字段值的副本,我需要證明,一旦城市獲得像

 Aberdeen 
     Aberdeen 
     Belfast 
     Birchington 
     Birmingham 
     Blackpool 
     Bournemouth 
     Brighton 
     Bristol 

我怎樣才能得到這個名單? Thinks to everyone !!

回答

0

試試這個

$querystr = " 
SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE post_id IN(  
SELECT DISTINCT wpostmeta.post_id 
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') AND meta_key ='city' 
"; 
$cities = $wpdb->get_results($querystr, OBJECT); 

<?php if ($cities): ?> 

    <?php global $post; ?> 
    <?php foreach ($cities as $c): ?>  
    <?php echo $c->meta_value; ?> <br />  
    <?php endforeach; ?> 

<?php endif; ?> 
+0

非常感謝您! –

0

SELECT後使用DISTINCT。它會刪除重複

$querystr = " 
    SELECT DISTINCT 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' 
";