代码之家  ›  专栏  ›  技术社区  ›  newtover

SQL中的表别名歧义在标准中是禁止的还是被实现阻止的?

  •  3
  • newtover  · 技术社区  · 14 年前

    昨天我第一次在SQL中遇到了一个歧义问题。我习惯了在表不明确的情况下使用SQL错误,昨天甚至没有尝试用这种方式来考虑这个问题。

    下面是一个简化的查询:

    SELECT
      val1,
      (
        SELECT SUM(val2) as val2_sum
        FROM (
          SELECT 1 as id, 10 as val2
          UNION ALL
          SELECT 2 as id, 10 as val2
        ) t
        WHERE id = t.id
      ) as val2_sum
    FROM (
      SELECT 1 as id, 'a' as val1
      UNION ALL
      SELECT 2 as id, 'b' as val1
    ) as t
    WHERE id = 1;
    

    结果:

    +------+----------+
    | val1 | val2_sum |
    +------+----------+
    | a    |       20 |
    +------+----------+
    

    预期结果:

    +------+----------+
    | val1 | val2_sum |
    +------+----------+
    | a    |       10 |
    +------+----------+
    

    问题是这里的两个表具有相同的别名,其中id=t.id总是1。

    该查询在MySQL和MS SQL中非常有效。但问题是,就SQL而言,它是否是一个bug。

    UPD : 正如@phil sandler所指出的,正如我在评论中注意到的,这里唯一的问题是两个具有union的表具有相同的别名t。将表的val2重命名为t2可以解决这个问题。

    2 回复  |  直到 14 年前
        1
  •  2
  •   onedaywhen    14 年前

    FROM

        2
  •  0
  •   Vinnie    14 年前

    SELECT
      val1
    , val2_sum
    FROM (
      SELECT 1 as id, 'a' as val1
      UNION ALL
      SELECT 2 as id, 'b' as val1
    ) as t
    join (SELECT id, SUM(val2) as val2_sum
            FROM (
          SELECT 1 as id, 10 as val2
          UNION ALL
          SELECT 2 as id, 10 as val2)
        as t GROUP BY id) t2 on t2.id = t.id
    WHERE t.id = 1;
    

    val2_sum 20