MySQL LEFT JOIN,其中连接表为null

时间:2011-12-28 22:00:45

标签: php mysql sql

我当前的SQL是:

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;

1 个答案:

答案 0 :(得分: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
    )