代码之家  ›  专栏  ›  技术社区  ›  Ashish Agarwal

有人能为MySQL推荐“intersect”和“minus”的替代方案吗?

  •  -1
  • Ashish Agarwal  · 技术社区  · 16 年前

    在MySQL(版本5.1)中出现以下查询错误

    SELECT year,month,sum(fact_1),sum(fact_2),sum(fact_3),sum(fact_4)
    from(
    select year,month,fact_1,fact_2,0 as fact_3,0 as fact_4 from table_1
    intersect
    select year,month,0 as fact_1,0 as fact_2,fact_3,fact_4 from table_2
    ) as combined_table
    group by month,year
    

    代码为1064的错误行:

    您的SQL语法有错误; 检查对应的手册 您的mysql服务器版本 在“select”附近使用的正确语法 年、月,0表示事实\1,0表示 表2中的事实\2、事实\3、事实\4 第5行CT G′

    但以下查询给出了所需的结果:

    SELECT year,month,sum(fact_1),sum(fact_2),sum(fact_3),sum(fact_4)
    from(
    select year,month,fact_1 ,fact_2,0 as fact_3,0 as fact_4 from table_1
    union
    select year,month,0 as fact_1,0 as fact_2,fact_3,fact_4 from table_2
    ) as ct
    group by month,year
    

    有人能告诉我犯了什么错误吗? 有人能帮我了解问题背后的根本原因吗?

    2 回复  |  直到 9 年前
        1
  •  5
  •   knittl    16 年前

    你可以伪造 INTERSECT 很容易使用 INNER (自我) JOIN ,这样您将只从两个结果集中获取行:

        SELECT `a`.`id`, `a`.`name`
          FROM `a`
    INNER JOIN `b`
         USING (`id`, `name`)
    

    MINUS 可以用一个 LEFT JOIN :

        SELECT DISTINCT `a`.`id`, `a`.`name`
          FROM `a`
     LEFT JOIN `b`
         USING (`id`, `name`)
         WHERE `b`.`id` IS NULL
    
        2
  •  0
  •   David M    16 年前

    MySQL不支持intersect关键字。5.1的select完整语法如下:

    http://dev.mysql.com/doc/refman/5.1/en/select.html