2014-02-13 76 views
3

我有這個腳本,從一個特定的類別中選擇一個列表:沒有類別中選擇後的wordpress

SELECT wp_posts.* 
    FROM wp_posts 
     LEFT JOIN wp_term_relationships 
       ON wp_posts.ID=wp_term_relationships.object_id 
     LEFT JOIN wp_term_taxonomy 
       ON wp_term_taxonomy.term_taxonomy_id = wp_term_relationships.term_taxonomy_id 
     LEFT JOIN wp_terms 
       ON wp_terms.term_id = wp_term_taxonomy.term_id 
WHERE wp_posts.post_type = 'post' 
    AND wp_posts.post_status = 'publish' 
    AND (
      wp_term_taxonomy.taxonomy = 'category' 
     AND wp_term_taxonomy.term_id = wp_terms.term_id 
     AND wp_terms.name = '$category' 
     ) 

如何選擇職位未分類的?我嘗試$category = ''並得到0行,因爲wp_terms.name =''沒有字段。

+0

WordPress的DB遵循實體 - 屬性值(EAV)模式,這使得複雜的查詢! – Andomar

回答

2

您可以使用where id is null條款要求該left join沒有成功:

SELECT p.* 
FROM wp_posts p 
LEFT JOIN 
     wp_term_relationships rel 
ON  p.ID = rel.object_id 
LEFT JOIN 
     wp_term_taxonomy tax 
ON  tax.term_taxonomy_id = rel.term_taxonomy_id 
     AND tax.taxonomy = 'category' 
LEFT JOIN 
     wp_terms term 
ON  term.term_id = tax.term_id 
WHERE p.post_type = 'post' 
     AND p.post_status = 'publish' 
     AND term.term_id is null -- No category found 

一個not exist子句可以用於在完成相同的:

SELECT * 
FROM wp_posts p 
WHERE p.post_type = 'post' 
     AND p.post_status = 'publish' 
     AND NOT EXISTS 
     (
     SELECT * 
     FROM wp_term_relationships rel 
     JOIN wp_term_taxonomy tax 
     ON  tax.term_taxonomy_id = rel.term_taxonomy_id 
       AND tax.taxonomy = 'category' 
     JOIN wp_terms term 
     ON  term.term_id = tax.term_id 
     WHERE p.ID = rel.object_id 
     ) 
+0

我得到#1054 - 'on子句'中的未知列'tax.term_taxonomy_id',是的,應該將其更改爲稅收 –

+0

該表的別名爲'tt',但引用爲'tax',現在應該修復。 – Andomar

相關問題