【问题标题】:sql subquery problemsql子查询问题
【发布时间】:2010-12-19 16:38:32
【问题描述】:

我不会说英语。

我有一个 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'

你能帮我解决这个问题吗?

【问题讨论】:

  • 您的英语足够好,可以在这里获得帮助。而且你的 SQL 也不错。
  • @dok 感谢您的好评

标签: mysql sql subquery mysql-error-1054


【解决方案1】:

您不能使用那里的字段名,因为它们在此范围内不可用。

你可以复制整个表达式

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;

【讨论】:

    【解决方案2】:

    我提供 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ış');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-08
      • 2018-01-17
      • 2011-12-05
      • 1970-01-01
      相关资源
      最近更新 更多