MySQL Union全部与MySQL Inner Join结合使用

时间:2016-06-20 05:14:54

标签: php mysql join union

我想从allinventory_tb获取说明和模型。

所以我做了内连接,但是当我要显示描述和模型时。

错误是这样的:

  

注意:未定义的索引:description,注意:未定义的索引:model。

有什么建议吗?

  |allinventory_tb|
  ----------------
  |in_code        |
  |description    |
  |model          |
  ---------------
    $sql = "select t.itemcode  as itemcode ,sum(t.qty) as qty
    from ( 
    select itemcode,qty  from barcode INNER JOIN allinventory_tb on barcode.itemcode = allinventory_tb.in_code
    union all
    select itemcode,qty from adjustment_tb INNER JOIN allinventory_tb on adjustment_tb.itemcode = allinventory_tb.in_code where adjustment_tb.status='APPROVED'
    union all
    select itemcode,(qty * -1) from soldout_pd INNER JOIN allinventory_tb on soldout_pd.itemcode = allinventory_tb.in_code) as t
    group by itemcode";

    $result = $conn->query($sql);

1 个答案:

答案 0 :(得分:1)

使用您的查询,

$sql = "select t.itemcode  as itemcode ,sum(t.qty) as qty
    from ( 
    select itemcode,qty  from barcode INNER JOIN allinventory_tb on barcode.itemcode = allinventory_tb.in_code
    union all
    select itemcode,qty from adjustment_tb INNER JOIN allinventory_tb on adjustment_tb.itemcode = allinventory_tb.in_code where adjustment_tb.status='APPROVED'
    union all
    select itemcode,(qty * -1) from soldout_pd INNER JOIN allinventory_tb on soldout_pd.itemcode = allinventory_tb.in_code) as t
    group by itemcode";


    $result = $conn->query($sql);

您将无法访问描述和模型列值,因为您未在查询中指定所需的列名,因此当您尝试在PHP中访问查询结果时,您将收到通知错误,如:

  

注意:未定义的索引:description,注意:未定义的索引:model。

尝试此查询

$sql = "select description,model,t.itemcode  as itemcode ,sum(t.qty) as qty
    from ( 
    select description,model,itemcode,qty  from barcode as bc INNER JOIN allinventory_tb as ait on bc.itemcode = ait.in_code
    union all
    select description,model,itemcode,qty from adjustment_tb as adt INNER JOIN allinventory_tb as ait1 on adt.itemcode = ait1.in_code where adjustment_tb.status='APPROVED'
    union all
    select description,model,itemcode,(qty * -1) from soldout_pd as slp INNER JOIN allinventory_tb as ait2 on slp.itemcode = ait2.in_code) as t
    group by itemcode";


$result = $conn->query($sql);

希望这对你有用......