1

我有两个共享同一列 ( 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
4

2 回答 2

1

您没有显示您的语法错误,但我猜您与以下行有关:

COUNT(C) AS CC

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

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

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

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
于 2012-10-24T22:16:02.873 回答
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
于 2012-10-24T22:19:47.803 回答