0

私は少し英語を話します。

SQLサブクエリエラーが発生しました

データベース:MySQL
テーブルタイプ:MyISAM

次の私のSQLクエリ

SELECT
(SELECT sum(`total`) FROM `staff_history` WHERE `type` = 'Giriş' AND staff_id = table_1.staff_id) AS `input`,
(SELECT sum(`total`) FROM `staff_history` WHERE `type` = 'Çıkış' AND staff_id = table_1.staff_id) AS `output`,
(`input` - `output`) AS `balance`
FROM `staff_history` AS `table_1` WHERE `staff_id` = '2';

このようなエラーが発生します

Error code 1054, SQL status 42S22: Unknown column 'input' in 'field list'

この問題について私を助けてくれませんか。

4

2 に答える 2

3

このスコープでは使用できないため、フィールド名をすでに使用することはできません。

式全体を複製できます

SELECT
(SELECT sum(`total`) FROM `staff_history` 
WHERE `type` = 'Giriş' AND staff_id = table_1.staff_id) AS `input`,
(SELECT sum(`total`) FROM `staff_history` 
WHERE `type` = 'Çıkış' AND staff_id = table_1.staff_id) AS `output`,
(SELECT sum(`total`) FROM `staff_history` 
WHERE `type` = 'Giriş' AND staff_id = table_1.staff_id) 
-
(SELECT sum(`total`) FROM `staff_history` 
WHERE `type` = 'Çıkış' AND staff_id = table_1.staff_id) AS `balance`
FROM `staff_history` AS `table_1` WHERE `staff_id` = '2';

クエリオプティマイザはこれを非常にうまく処理しますが、あまり保守しにくいため、クエリ全体をサブクエリに入れることもできます。

SELECT
  x.`input`,
  x.`output`,
  x.`input` - x.`output` as `balance`
FROM
  (SELECT
    (SELECT sum(`total`) 
    FROM `staff_history` 
    WHERE `type` = 'Giriş' AND staff_id =  table_1.staff_id) AS `input`,
    (SELECT sum(`total`) 
    FROM `staff_history` 
    WHERE `type` = 'Çıkış' AND staff_id = table_1.staff_id) AS `output`
  FROM 
    `staff_history` AS `table_1` 
  WHERE `staff_id` = '2') x;
于 2010-12-19T16:43:41.793 に答える
0

1つのSQLステートメントと1つのテーブルスキャンを提供します。

select sum(case when type = 'Giriş' then total else 0 end) as input
      ,sum(case when type = 'Çıkış' then total else 0 end) as output
      ,sum(case when type = 'Giriş' then total else 0 end) - 
       sum(case when type = 'Çıkış' then total else 0 end) as balance
  from staff_history
 where staff_id = 2
   and type in('Giriş', 'Çıkış');
于 2010-12-19T18:40:59.503 に答える