mysql子查询嵌套传递值

时间:2016-12-17 13:38:09

标签: mysql

我在MySql上有这个查询:

SELECT id , ( 

    SELECT IFNULL(SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(tfo.a,  tfo.da)))),'00:00')  as tempo
    FROM (
        SELECT DISTINCT gg_settimana, id_fascia 
        FROM operatori_piano
        WHERE id_istruttore = o.id
    ) as sa
    LEFT JOIN tab_fasce_orarie as tfo ON tfo.id = sa.id_fascia

) as tempo
FROM operatori as o 
WHERE tipo = 2 AND attivo = 1

Mysql返回此错误:

Error Code: 1054. Unknown column 'o.id' in 'where clause'

我尝试了很多组合,但没有工作。 请帮助,非常感谢!

2 个答案:

答案 0 :(得分:0)

发生错误的原因是您将select语句嵌套在查询中的select内,该查询将o命名为别名。别名仅在直接子查询中可见。

如果没有很多有关您的架构的更多信息,则无法建议正确,有效的解决方案是什么(使用我们所知的模式正确的架构来生成查询是直截了当的,但是它可能在功能上不正确)。但是,作为一般经验法则,请尝试避免相关的子查询(推送谓词)。除了通常不利于维护和性能之外,MySQL在优化此类查询方面也很差。

答案 1 :(得分:0)

在子查询中不可访问但是查看代码的别名可以避免使用内部联接引用外部选择

  SELECT id , ( 

      SELECT IFNULL(SEC_TO_TIME(SUM(TIME_TO_SEC(TIMEDIFF(tfo.a,  tfo.da)))),'00:00')  as tempo
      FROM (
          SELECT DISTINCT gg_settimana, id_fascia 
          FROM operatori_piano
          INNER JOIN operatori as o ON  id_istruttore = o.id
          WHERE o.tipo = 2 AND o.attivo = 1
      ) as sa
      LEFT JOIN tab_fasce_orarie as tfo ON tfo.id = sa.id_fascia

  ) as tempo
  FROM operatori 
  WHERE tipo = 2 AND attivo = 1