如何从mysql中的临时表中选择子查询

时间:2016-03-16 09:47:17

标签: mysql sql database

我有tmp表从三个表收集联合数据并且它正常工作当尝试从这个tmp表中选择任何列作为子查询时问题开始,但我想这样做因为我将从tmp表结果进行计算,那怎么做呢

我看到此错误消息

  

[42S02] [1146]表'projectdb.tmp'不存在

此代码的问题

(SELECT stquantity ) AS SB

我的代码是

SELECT tmp.it_code,(SELECT tmp.stquantity ) AS SB
FROM (
  SELECT
    tm.it_code AS it_code,
    2          AS ts_type,
    (
      SELECT SUM(rrg1.rpog_quantity)
      FROM d_repo_returned rpr1, d_repo_returned_grid AS rrg1
      WHERE rrg1.rpog_send_main_id = rpr1.rpo_id
            AND rrg1.rpog_item_id = tm.it_id
            AND rpr1.rpo_returned_date <= 1457996475

    )          AS stquantity,
    (SELECT SUM(rrg2.rpog_quantity)
     FROM d_repo_returned rpr2, d_repo_returned_grid AS rrg2
     WHERE rrg2.rpog_send_main_id = rpr2.rpo_id
           AND rrg2.rpog_item_id = tm.it_id
           AND rpr2.rpo_returned_date <= 1459375315

    )          AS edquantity

  FROM d_repo_returned, d_repo_returned_grid, d_items AS tm
  WHERE rpog_send_main_id = rpo_id
        AND rpog_item_id = tm.it_id
  GROUP BY tm.it_code
  UNION ALL
  SELECT
    ts.it_code AS it_code,
    3          AS ts_type,
    (
      SELECT SUM(stg1.sig_quantity)
      FROM d_send_items str1, d_send_items_grid AS stg1
      WHERE stg1.sig_send_main_id = str1.si_id
            AND stg1.sig_item_id = ts.it_id
            AND str1.si_send_date <= 1457996475

    )          AS stquantity,
    (SELECT SUM(stg2.sig_quantity)
     FROM d_send_items str2, d_send_items_grid AS stg2
     WHERE stg2.sig_send_main_id = str2.si_id
           AND stg2.sig_item_id = ts.it_id
           AND str2.si_send_date <= 1459375315

    )          AS edquantity
  FROM d_send_items str, d_send_items_grid stg, d_items AS ts
  WHERE stg.sig_send_main_id = str.si_id
        AND stg.sig_item_id = ts.it_id
  GROUP BY ts.it_code
  UNION ALL
  SELECT
    di.it_code             AS it_code,
    1                      AS ts_type,
    (SELECT SUM(di1.it_quantity)
     FROM d_items di1
     WHERE di1.it_code = di.it_code AND di1.it_date <= 1457996475
     GROUP BY di1.it_code) AS stquantity,
    (SELECT SUM(di2.it_quantity)
     FROM d_items di2
     WHERE di2.it_code = di.it_code AND di2.it_date <= 1459375315
     GROUP BY di2.it_code) AS edquantity
  FROM d_items di
  GROUP BY di.it_code
) AS tmp

1 个答案:

答案 0 :(得分:0)

尝试更改第一行(SELECT tmp.it_code,(SELECT stquantity)AS SB) 到

SELECT it_code, stquantity AS SB

这是我从您的查询中可以理解的。 :)