MySQL中的SELECT语法问题

时间:2014-03-28 10:54:44

标签: php mysql sql

我尝试了以下语法,当我使用Oracle SQL Developer时,它似乎在SQL上运行良好。但是,当我在MySQL中使用代码时,我得到了错误"出了问题!"。

   $result = mysqli_query($con, "SELECT * FROM Table1 NATURAL JOIN (SELECT ID, SUM(row2) FROM table2 GROUP BY ID) NATURAL JOIN (SELECT ID, COUNT(col1) FROM Table2 WHERE ID IS NOT NULL GROUP BY ID)")
   or die("Something went wrong!");

在这种情况下,语法是否存在差异,或者它可能是我做错的其他事情?

谢谢!

2 个答案:

答案 0 :(得分:0)

这是您的查询:

SELECT *
FROM Table1 NATURAL JOIN
      (SELECT ID, SUM(row2) FROM table2 GROUP BY ID) NATURAL JOIN
      (SELECT ID, COUNT(col1) FROM Table2 WHERE ID IS NOT NULL GROUP BY ID)

MySQL支持NATURAL JOIN(我不建议使用它,但这是另一回事)。与Oracle不同,您需要在表上具有表别名,基本上是它们的名称。您可能还需要列别名。我总是使用它们,所以我不知道是否需要它们。

试试这个:

SELECT *
FROM Table1 t1 NATURAL JOIN
      (SELECT ID, SUM(row2) as cnt_row2
       FROM table2
       GROUP BY ID
      ) t2row NATURAL JOIN
      (SELECT ID, COUNT(col1) as cnt_col1
       FROM Table2
       WHERE ID IS NOT NULL
       GROUP BY ID
      ) t2col1

您实际上可以简化此查询:

SELECT t1.*, t2.cnt_col1, t2.cnt_row2
FROM Table1 t1 INNER JOIN
      (SELECT ID, COUNT(col1) as cnt_col1, SUM(row2) as cnt_row2
       FROM Table2
       GROUP BY ID
      ) t2
      ON t1.id = t2.id

ID IS NOT NULL上的过滤无效,因为NULL中不会包含join值。

答案 1 :(得分:-1)

在MySQL中,FROM部分中使用的所有Sub查询都需要别名。在你的情况下,它失踪了。我不使用NATURAL JOIN因为使用其他特定INNER JOINLEFT JOIN来澄清条件和方案。因此,您可以像这样重写您的查询以使其正常工作:

SELECT * FROM Table1
INNER JOIN (SELECT ID, SUM(row2) FROM table2 GROUP BY ID) a
ON a.ID = Table1.ID
INNER JOIN (SELECT ID, COUNT(col1) FROM Table2 WHERE ID IS NOT NULL GROUP BY ID) b
ON b.ID = Table2.ID;