Drupal 7 db_select嵌套选择查询

时间:2012-12-11 10:35:48

标签: mysql sql drupal drupal-7 drupal-modules

如何将嵌套的选择查询转换为Drupal 7 db_select?以下是问题查询:

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

1 个答案:

答案 0 :(得分:5)

在语义上它非常简单:

$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();