任何人都可以提出“交叉”的替代方案; MYSQL的“减号”?

时间:2009-09-03 09:17:10

标签: mysql mysql-error-1064

MYSQL(version5.1)中以下查询的GOT错误

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为fact_1,0 as   fact_2,fact_3,fact_2从table_2)as   ct g'在第5行

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

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 个答案:

答案 0 :(得分:5)

您可以使用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

答案 1 :(得分:0)

MySQL不支持INTERSECT关键字。 SELECT for 5.1的完整语法如下:

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