SQL加入“上升”两个表

时间:2010-05-19 16:44:41

标签: sql join left-join

我正在尝试使用连接创建一个中等复杂的查询:

SELECT `history`.`id`,  
       `parts`.`type_id`, 
       `serialized_parts`.`serial`, 
       `history_actions`.`action`, 
       `history`.`date_added`
FROM `history_actions`, `history`
LEFT OUTER JOIN `parts` ON `parts`.`id` = `history`.`part_id`
LEFT OUTER JOIN `serialized_parts` ON `serialized_parts`.`parts_id` = `history`.`part_id`
WHERE `history_actions`.`id` = `history`.`action_id` 
  AND `history`.`unit_id` = '1' 
ORDER BY `history`.`id` DESC

我想用`part_list` .name`替换SELECT语句中的`parts` .type_id`,其中我需要在两个表之间强制执行的关系是`part_list` .id` =`parts `.`type_id`。此外,我必须使用连接,因为在某些情况下`history` .part_id`可能是NULL,这显然不是有效的部件ID。如何修改查询以执行此操作?

以下是请求的一些示例日期: 历史表:
alt text http://ianburris.com/dropbox/public/so/q1/history.jpg
serialized_pa​​rts表:
alt text http://ianburris.com/dropbox/public/so/q1/serialized_parts.jpg
零件表:
alt text http://ianburris.com/dropbox/public/so/q1/parts.jpg
part_list表:
alt text http://ianburris.com/dropbox/public/so/q1/part_list.jpg

我想看到的是:

id  name           serial    action   date_added
4   Battery        567     added    2010-05-19 10:42:51
3   Antenna Board  345     added    2010-05-19 10:42:51
2   Main Board     123     added    2010-05-19 10:42:51
1   NULL           NULL    created  2010-05-19 10:42:51

2 个答案:

答案 0 :(得分:2)

这至少会走上正轨......

如果您希望不显示任何ID无效的部分,只需将LEFT JOIN更改为INNER JOIN(它们将限制NULL值)

    SELECT `history`.`id`  
         , `parts`.`type_id`
         , `part_list`.`name`
         , `serialized_parts`.`serial`
         , `history_actions`.`action` 
         , `history`.`date_added`
      FROM `history_actions`
INNER JOIN `history` ON `history`.`action_id` = `history_actions`.`id`
 LEFT JOIN `parts` ON `parts`.`id` = `history`.`part_id`     
 LEFT JOIN `serialized_parts` ON `serialized_parts`.`parts_id` = `history`.`part_id`
 LEFT JOIN `part_list` ON `part_list`.`id` = `parts`.`type_id`
     WHERE `history`.`unit_id` = '1' 
  ORDER BY `history`.`id` DESC

答案 1 :(得分:0)

男孩,这些反叛让我的眼睛受伤了。

SELECT
  h.id,  
  p.type_id, 
  pl.name,
  sp.serial, 
  ha.action, 
  h.date_added
FROM
  history                     h
  INNER JOIN history_actions ha ON ha.id       = h.action_id
  LEFT JOIN parts             p ON p.id        = h.part_id
  LEFT JOIN serialized_parts sp ON sp.parts_id = h.part_id
  LEFT JOIN part_list        pl ON pl.id       = p.type_id
WHERE 
  h.unit_id = '1' 
ORDER BY
  history.id DESC