来自3个表的Oracle Query

时间:2014-05-09 02:43:29

标签: php sql oracle

从3个表(FABRICATION, FABRICATION_QC, AND WEIGHT)查询数据并在PHP中使用它们的值时遇到问题。我的查询是这样的:

select fabrication.*,master_drawing.weight,
                (select fabrication_qc.marking_qc from fabrication_qc where fabrication_qc.head_mark=fabrication.head_mark) MARKING_QC,
                (select fabrication_qc.marking_qc_date from fabrication_qc where fabrication_qc.head_mark=fabrication.head_mark) MARKING_QC_DATE,
                (select fabrication_qc.marking_qc_sign from fabrication_qc where fabrication_qc.head_mark=fabrication.head_mark) MARKING_QC_SIGN
                from fabrication,fabrication_qc,master_drawing
                where fabrication.head_mark = master_drawing.head_mark";

当我在PHP中执行此操作以将该数据放入表中时,

while (($row = oci_fetch_array($fabParse, OCI_BOTH)) != false) 
    { 
        echo '<tr>';
            echo '<td>'.$row['PROJECT_NAME'].'</td>';
            echo '<td>'.$row['HEAD_MARK'].'</td>';
            echo '<td>'.$row['ID'].'</td>';

            var_dump($row['MARKING_QC']);

PROJECT_NAMEHEAD_MARKID工作正常。只有转储的MARKING_QC在输出中显示NULL

谁能告诉我这里我做错了什么?

2 个答案:

答案 0 :(得分:1)

我假设这是你真正想要的查询:

select f.*, md.weight,
       (select fqc.marking_qc from fabrication_qc fqc where fqc.head_mark = f.head_mark) as MARKING_QC,
       (select fqc.marking_qc_date from fabrication_qc fqc where fqc.head_mark = f.head_mark) as MARKING_QC_DATE,
       (select fqc.marking_qc_sign from fabrication_qc fqc where fqc.head_mark = f.head_mark) as MARKING_QC_SIGN
from fabrication f join
     master_drawing md
     on f.head_mark = md.head_mark;

这将删除外部fabrication_qc子句中的引用from。这只会导致不必要的笛卡尔积。我还引入了表别名以使查询更具可读性。并且,使用适当的显式连接语法而不是隐式连接。

您可以进一步将其简化为:

select f.*, md.weight,
       fqc.marking_qc, fqc.marking_qc_date, fqc.marking_qc_sign
from fabrication f join
     master_drawing md
     on f.head_mark = md.head_mark left outer join
     fabrication_qc fqc
     on fqc.head_mark = f.head_mark

答案 1 :(得分:1)

我会写这样的查询:

select 
  f.project_name,
  f.head_mark,
  f.id,
  m.weight,
  qc.marking_qc, 
  qc.marking_qc_date,
  qc.marking_qc_sign 
from fabrication as f 
join master_drawing as m
  on  f.head_mark = m.head_mark
left outer join fabrication_qc as qc      
  on  f.head_mark = qc.head_mark

--  where (no criteria given)
;

尝试从代码外部的查询执行工具运行查询,以确认结果。