2012-12-11 118 views
4

如何將嵌套的select查詢轉換爲Drual 7 db_select?以下是問題查詢:Drupal 7 db_select嵌套選擇查詢

select 
    * 
from 
    tbl_word 
where 
    EngWord like '%apple%' or 
    WordID in (
     select 
      WordID 
     from 
      tbl_subword 
     where 
      EngWord like '%apple%' 
    ); 
+0

看到http://thanhnp.wordpress.com/2011/09/15/write-a-sub-query-by -db_select-drupal7/ – user7282

回答

5

語義上它是非常simliar:

$term = 'apple'; 

$sub_query = db_select('tbl_subword') 
    ->fields('tbl_subword', array('WordID')) 
    ->condition('EngWord', '%' . db_like($term) . '%'), 'LIKE'); 

$query = db_select('tbl_word') 
    ->fields('tbl_word') 
    ->condition(db_or() 
    ->condition('EngWord', '%' . db_like($term) . '%', 'LIKE') 
    ->condition('WordID', $sub_query, 'IN') 
); 

$results = $query->execute()->fetchAll(); 
+0

如果在主查詢中不會產生AND,我認爲他需要在子查詢中使用OR術語? – KerrM

+0

@KerrM好點我錯過了,回答更新 – Clive

+0

太棒了!它的工作正常。只是在導致解析錯誤的情況下修復額外的內存。 – Cyber