2014-06-25 580 views
0

我正在爲WordPress編寫一個SQL查詢,用於搜索用戶搜索之間的活動事件。我現在正在對它進行硬編碼測試。SQL返回重複結果

目前,每當post_id出現在wp_postmeta表中時,都會返回兩個事件,任何人都可以看到哪裏可能存在這個邏輯的問題?

SELECT ID, post_title 
    FROM $wpdb->posts AS post 
    INNER JOIN $wpdb->postmeta AS meta 
    ON (post.ID = meta.post_id) 
    INNER JOIN $wpdb->postmeta AS meta2 
    ON (post.ID = meta2.post_id) 
    WHERE post.post_status = 'publish' 
    AND post.post_type = 'event' 
    AND post.post_author = '1' 
    AND (
      ((meta.meta_key = 'date_0_start-date' AND meta.meta_value < '20140620') AND (meta2.meta_key = 'date_0_end-date' AND meta2.meta_value > '20140630')) 
     OR ((meta.meta_key = 'date_0_start-date' AND meta.meta_value < '20140620') AND (meta2.meta_key = 'date_0_end-date' AND meta2.meta_value >= '20140620')) 
     OR ((meta.meta_key = 'date_0_start-date' AND meta.meta_value > '20140620') AND (meta.meta_key = 'date_0_start-date' AND meta.meta_value <= '20140630')) 
     OR ((meta.meta_key = 'date_0_start-date' AND meta.meta_value >= '20140620') AND (meta2.meta_key = 'date_0_end-date' AND meta2.meta_value <= '20140630')) 
    ) 

回答

1

你必須使用DISTINCT

SELECT DISTINCT ID, post_title

,而不是

SELECT ID, post_title

+0

完美!謝謝! – lukeseager

1

如果我理解正確的問題,我想你需要的最後一個括號部分where clause to look like this

meta.meta_key = 'date_0_start-date' AND meta.meta_value <= '20140630' and 
meta2.meta_key = 'date_0_end-date' AND meta2.meta_value >= '20140620' 

這應該與重疊的日期範圍「20140620」的任何事件爲「20140630」

+0

謝謝,這比我的查詢更容易閱讀 – lukeseager