mysql中子查询中的语法错误

时间:2014-10-30 16:22:50

标签: mysql sql

我从这段代码中得到#1064错误我试图在values命令中使用子查询我是mySQL的新手并且无法发现错误。

CREATE TEMPORARY TABLE TempTable(myid INT,points INT)
INSERT INTO TempTable
values(1,
points
(
 SELECT player.team, COUNT( * ) AS count
 FROM playerpoints
 JOIN player ON playerpoints.PlayerID = player.PlayerID
 WHERE player.team = 'ManU'
 AND EXTRACT( MONTH FROM playerpoints.date ) <07
 GROUP BY player.team
));

INSERT INTO TempTable
values(2,
points
(
  SELECT player.team, COUNT( * ) AS count2
  FROM playerpoints
  JOIN player ON playerpoints.PlayerID = player.PlayerID
  WHERE player.team = 'ManU'
  AND EXTRACT( MONTH FROM playerpoints.date ) >07
 GROUP BY player.team
));

DROP TABLE TempTable;

2 个答案:

答案 0 :(得分:1)

您要使用的构造是INSERT INTO ... SELECT ...。您不使用子查询(或VALUES关键字)。

INSERT INTO TempTable (myid, points)
SELECT player.team, COUNT( * ) AS count
FROM playerpoints
JOIN player ON playerpoints.PlayerID = player.PlayerID
WHERE player.team = 'ManU'
AND EXTRACT( MONTH FROM playerpoints.date ) <07
GROUP BY player.team;

基本上,您希望SELECT返回您正在插入的行(按照正确的顺序)。

文档:http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

答案 1 :(得分:0)

第一行末尾没有分号。此外,INSERT语法可以稍微清理一下。最后,不需要GROUP BY子句。试试这个:

试试这个:

CREATE TEMPORARY TABLE TempTable(myid INT,points INT);

INSERT INTO TempTable
values(1, (
  SELECT COUNT( * )
  FROM playerpoints
  JOIN player ON playerpoints.PlayerID = player.PlayerID
  WHERE player.team = 'ManU'
  AND EXTRACT( MONTH FROM playerpoints.date ) <07
));

INSERT INTO TempTable
values(2, (
  SELECT COUNT( * )
  FROM playerpoints
  JOIN player ON playerpoints.PlayerID = player.PlayerID
  WHERE player.team = 'ManU'
  AND EXTRACT( MONTH FROM playerpoints.date ) >07
));

...

DROP TABLE TempTable;

这假设playerpoints每个条目记录一个点。否则,您需要SELECT SUM(playerpoints.points)而不是SELECT COUNT(*)