-1

在过去的几天里,我正在尝试解决这个问题,任何帮助将不胜感激。

我有一个退货项目,它在 taxonomy1 中有 term1,在 taksonomy2 中有 term2。

这是我的查询:

SELECT items.*
FROM (`items`)
LEFT JOIN `rel_taxonomy` ON `rel_taxonomy`.`item_id` = `items`.`id`
LEFT JOIN `terms_taxonomy` ON `terms_taxonomy`.`terms_taxonomy_id` = `rel_taxonomy`.`terms_taxonomy_id`
LEFT JOIN `terms` ON `term`.`id` = `terms_taxonomy`.`term_id`
WHERE (items.org =  '2')  AND  ( ((terms_taxonomy.taxonomy =  '1') AND (term.pojam  LIKE '%term1%')) AND ((terms_taxonomy.taxonomy =  '2') AND (term.pojam  LIKE '%term2%')))  
GROUP BY `items`.`id`

如果我替换该行:

WHERE (items.org =  '2')  AND  ( ((terms_taxonomy.taxonomy =  '1') AND (term.pojam  LIKE '%term1%')) AND ((terms_taxonomy.taxonomy =  '2') AND (term.pojam  LIKE '%term2%')))

使用以下内容(将 AND 替换为 OR):

WHERE (items.org =  '2')  AND  ( ((terms_taxonomy.taxonomy =  '1') AND (term.pojam  LIKE '%term1%')) OR((terms_taxonomy.taxonomy =  '2') AND (term.pojam  LIKE '%term2%')))  

一切正常。但我仍然需要AND。

表方案

items
id | title | org

rel_taxonomy
item_id | terms_taxonomy_id

terms_taxonomy
terms_taxonomy_id | terms_id | taxsonomy 

terms
id | term

所以我试图获得在taxonomy1中有term1和在taksonomy2中有term2的项目。

4

1 回答 1

0

使用OR和添加HAVING子句

 SELECT i.id
 FROM items i
 LEFT JOIN rel_taxonomy rt ON rt.item_id = i.id
 LEFT JOIN terms_taxonomy tt ON tt.terms_taxonomy_id = rt.terms_taxonomy_id
 LEFT JOIN terms t ON t.id = tt.term_id
 WHERE i.org =  '2'
 AND 
 ( 
        (tt.taxonomy =  '1' AND t.pojam  LIKE '%term1%') 
     OR (tt.taxonomy =  '2' AND t.pojam  LIKE '%term2%')
 )  
 GROUP BY i.id
 having count(distinct tt.taxonomy) = 2
于 2012-11-23T11:17:53.190 回答