为什么这个SQL查询不断向我显示语法错误

时间:2013-10-23 16:09:44

标签: mysql sql syntax

语法错误显示在以下代码中的“as t3”。 我试图完全外连接2个表,但由于mysql没有完全连接,我使用union来联合2左/右连接表。 对我来说,我找不到任何语法错误,但它只是不起作用......

SELECT 
    name, f.author_nameauthor_id, c1, c2 
FROM 
(
    SELECT 
          author_id, c1, c2 
    FROM 
    (
        (SELECT 
               author_id, amount AS c1 
         FROM Author_Keyword_Count 
         WHERE keyword_id=19478) AS t1 

         LEFT OUTER JOIN 

        (SELECT 
               author_id, amount AS c2 
         FROM Author_Keyword_Count 
         WHERE keyword_id=33944) AS t2 

         ON author_id=author_id
    ) 
    UNION 
    (
        (SELECT author_id, amount AS c1 FROM Author_Keyword_Count WHERE keyword_id=19478) AS t3 
         RIGHT OUTER JOIN 
        (SELECT author_id, amount AS c2 FROM Author_Keyword_Count WHERE keyword_id=33944) AS t4 
         ON author_id=author_id
    )
) AS f 

LEFT OUTER JOIN Author ON author_id=id;

1 个答案:

答案 0 :(得分:0)

下面列出了一些观察结果......

SELECT name
     , f.author_nameauthor_id
     , c1
     , c2 
  FROM 
     ( SELECT author_id
            , c1
            , c2 
         FROM 
            (   !-- <-- something missing here!?!
                  ( SELECT author_id
                         , amount c1 
                      FROM Author_Keyword_Count 
                     WHERE keyword_id = 19478
                  ) t1 
               LEFT
               JOIN
                  ( SELECT author_id
                         , amount c2 
                      FROM Author_Keyword_Count 
                     WHERE keyword_id = 33944
                  ) t2 
                 ON author_id = author_id !-- <-- which author id equals which other author id!?!? 
            ) 
        UNION 
            (  !-- <-- something missing here!?!?
                ( SELECT author_id
                       , amount c1 
                    FROM Author_Keyword_Count 
                   WHERE keyword_id = 19478
                ) t3 
            RIGHT 
             JOIN  !-- for ease of conceptualising, consider restructuring your logic to use a LEFT JOIN instead of a RIGHT JOIN
                ( SELECT author_id
                       , amount c2 
                    FROM Author_Keyword_Count 
                   WHERE keyword_id = 33944
                ) t4 
               ON author_id = author_id !-- <-- which author id equals which other author id!?!?  
            )
      ) f 
   LEFT
   JOIN Author 
     ON author_id = id;  !-- <-- which author id equals which id!?!? 

从概念上讲,您撰写的(SELECT 'x') a JOIN (SELECT 'y') b我认为)无效。您可以改为编写SELECT * FROM (SELECT 'x') a JOIN (SELECT 'y') b,但也许有更优雅的方式构建此查询 - 只要我们知道您实际上想要做什么。