2011-12-28 49 views
0

我现在的SQL是:MySQL的左连接,其中连接表是空

SELECT * FROM `node` 
LEFT JOIN `field_data_field_area_of_study_category` 
ON `field_data_field_area_of_study_category`.`entity_id` = `node`.`nid` 
WHERE `node`.`type` = 'area_of_study' 
GROUP BY `node`.`nid` 

现在,使其工作,我在列运行foreach环路is_null()

我试图在SQL查询中模拟is_null()检查。

感谢您的阅读。

编辑 这是运行is_null() foreach循环。我认为更好的方式来问我的问题将是:如何使SQL返回只有行从节点表中没有匹配的field_data_field_area_of_study_category表?

foreach($aos_nodes as $aos_node): 
    if (is_null($aos_node->field_area_of_study_category_tid)): 
    $menu_item_display[$aos_node->title] = array(
     'id' => $aos_node->nid, 
     'type' => 'node', 
     'children_markup' => '', 
     'icon' => '', 
     'name' => $aos_node->title, 
     'href' => drupal_get_path_alias('node/'.$aos_node->nid), 
    ); 
    endif; 
endforeach; 
+3

有什么问题吗? – 2011-12-28 22:02:02

+2

更具体到@SergeiTulentsev - 如果加入的值为空,你想要做什么? – Eric 2011-12-28 22:03:10

+2

'WHERE field IS NULL'? ['ISNULL(场)'](http://dev.mysql.com/doc/refman/5.0/en/comparison-operators.html#function_isnull)? ['IFNULL(field,0)'](http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_ifnull)? – 2011-12-28 22:03:53

回答

5

要返回行那里没有匹配的一个:

SELECT * FROM `node` 
LEFT JOIN `field_data_field_area_of_study_category` 
ON `field_data_field_area_of_study_category`.`entity_id` = `node`.`nid` 
WHERE `node`.`type` = 'area_of_study' 
    and `field_data_field_area_of_study_category`.`entity_id` is null 
GROUP BY `node`.`nid` 

此外,还可以使用not exists

select 
    * 
from 
    node n 
where 
    n.type = 'area_of_study' 
    and not exists (
     select 
      1 
     from 
      field_data_field_area_of_study_category f 
     where 
      f.entity_id = n.nid 
    ) 
+0

添加了一个回答w /社区Wiki来放弃代表点,但至少可以在那里得到您需要的答案。 – Eric 2011-12-28 22:11:39

+0

这正是我所需要的。我一直在努力寻找使用ON语法在LEFT JOINing时过滤结果的方法,但这是我寻找的110%。谢谢! – 2011-12-28 22:13:42

+1

啊,是的,那个错误。值得一提的是,'ON'绝不会过滤掉行,它只能指定一个表中的哪些行属于另一个表的行。连接类型和where子句是过滤行的两件事。这是一个微妙的差异(尤其是内部连接),但是当你编写越来越复杂的SQL时,这一点非常重要。 – Eric 2011-12-28 22:17:00