在SQL中连接两个表

时间:2012-10-24 22:13:09

标签: mysql sql

我有两个共享相同列的表(C),但SQL告诉我我有错误

以下是第一个查询中的第一个表:

SELECT   E.C AS C, 
         COUNT(C) AS CC
FROM     E
GROUP BY E.C

这是第二个查询:

SELECT   E.C AS C, 
         COUNT(C) AS Num
FROM     E, G
WHERE    E.G = G.L
         AND G.G <
                    (SELECT min(G.G) 
                     FROM   G
                     WHERE  G.L = "BLAH")

GROUP BY E.C

所以我试着简单地将这两者放在一起,将JOIN放在它们之间。但即使它们共享同一列C,也不会加入它们。它只是说我有语法错误。怎么了?我该如何解决?我已经确认,当单独运行时,它们会使用列C

生成正确的输出

以下是JOIN执行总数

(SELECT   E.C AS C, 
             COUNT(C) AS CC
    FROM     E
    GROUP BY E.C)

JOIN

(SELECT   E.C AS C, 
             COUNT(C) AS Num
    FROM     E, G
    WHERE    E.G = G.L
             AND G.G <
                        (SELECT min(G.G) 
                         FROM   G
                         WHERE  G.L = "BLAH")

    GROUP BY E.C)

错误是 错误代码1064,SQL状态42000:您的SQL语法中有错误;检查与您的MySQL服务器版本对应的手册,以便在'JOIN

附近使用正确的语法
(SELECT   E.C AS C, 
         COUNT(C) AS Num' at line 6
Line 1, column 1

2 个答案:

答案 0 :(得分:1)

您没有显示您的语法错误,但我猜您将使用以下行:

COUNT(C) AS CC

由于两个表都有一列C,因此查询不知道从哪个表返回值。您需要在表名或别名前加上它。

此行适用于您的第一个查询,因为您只有一个名为C的列,一旦您有两个列,您需要指定要返回的列。

根据您的编辑,您缺少子查询的别名和连接的开启条件:

select t1.C, t1.cc, t2.num
from 
(
    SELECT   E.C AS C, 
             COUNT(C) AS CC
    FROM     E
    GROUP BY E.C
) t1  -- added alias
INNER JOIN
(
    SELECT   E.C AS C, 
             COUNT(E.C) AS Num  -- added table name, since column c exists in both tables
    FROM    E 
    JOIN    G
        ON E.G = G.L
    WHERE  G.G < (SELECT min(G.G) 
                   FROM   G
                   WHERE  G.L = "BLAH")
    GROUP BY E.C
) t2  -- added alias
    on t1.C = t2.C  -- added on clause

答案 1 :(得分:1)

试试这个:

select Z.C /*other*/ 
from (SELECT   E.C AS C, 
               COUNT(E.C) AS CC
      FROM     E
      GROUP BY E.C) Z

JOIN (SELECT   E.C AS C, 
             COUNT(E.C) AS Num
       FROM     E, G
       WHERE    E.G = G.L
                AND G.G < (SELECT min(G.G) 
                           FROM   G
                          WHERE  G.L = "BLAH")    
       GROUP BY E.C) Y on Y.C = Z.C