MySql select语句有效,但不能删除

时间:2014-09-29 09:19:35

标签: mysql select where sql-delete sql-subselect

SET @UserID_In = 1;
Select * FROM EarnedTransaction AS ETMain WHERE ETMain.UserID = @UserID_In
  AND ETMain.ID = ( SELECT MAX(ID) FROM EarnedTransaction AS ETSub WHERE ETSub.UserID = 
    ETMain.UserID AND ETSub.TransactionType = 'Buying' AND ETSub.CompleteDate IS NULL )
  AND ETMain.ID = ( SELECT MAX(ID) FROM EarnedTransaction AS ETSub WHERE ETSub.UserID =             
    ETMain.UserID );

返回34 15 Buying 1500 1428101231 1 2014-09-29 10:09:55

但:

SET @UserID_In = 1;
Delete FROM EarnedTransaction AS ETMain WHERE ETMain.UserID = @UserID_In
   AND ETMain.ID = ( SELECT MAX(ID) FROM EarnedTransaction AS ETSub WHERE ETSub.UserID = 
       ETMain.UserID AND ETSub.TransactionType = 'Buying' AND ETSub.CompleteDate IS NULL )
   AND ETMain.ID = ( SELECT MAX(ID) FROM EarnedTransaction AS ETSub WHERE ETSub.UserID =                   
       ETMain.UserID );

返回: [Err] 1064 - You have an error in your SQL syntax;检查与您的MySQL服务器版本对应的手册,以便在第1行AS ETMain WHERE ETMain.UserID = @UserID_In AND ETMain.ID = ( SELECT MAX(ID)附近使用正确的语法

2 个答案:

答案 0 :(得分:2)

尝试此删除查询(没有"删除表&#34的别名):

SET @UserID_In = 1;
DELETE FROM EarnedTransaction 
      WHERE UserID = @UserID_In
        AND ID = (SELECT MAX(ID) 
                    FROM EarnedTransaction AS ETSub 
                   WHERE ETSub.UserID = UserID 
                     AND ETSub.TransactionType = 'Buying' 
                     AND ETSub.CompleteDate IS NULL)
        AND ID = (SELECT MAX(ID) 
                    FROM EarnedTransaction AS ETSub 
                   WHERE ETSub.UserID = UserID );

答案 1 :(得分:1)

我得到了以下简化。在某些时候,你可能意味着不同的东西。

原文,格式化:

SET @UserID_In = 1;
DELETE FROM EarnedTransaction AS ETMain WHERE ETMain.UserID = @UserID_In
AND ETMain.ID = (
     SELECT MAX(ID)
     FROM EarnedTransaction AS ETSub
     WHERE ETSub.UserID = ETMain.UserID
     AND ETSub.TransactionType = 'Buying'
     AND ETSub.CompleteDate IS NULL )
AND ETMain.ID = (
     SELECT MAX(ID)
     FROM EarnedTransaction AS ETSub
     WHERE ETSub.UserID = ETMain.UserID );

第一个子查询和第二个子查询减少到第一个子查询。也许是像OR-ELSE这样的东西?

SET @UserID_In = 1;
DELETE FROM EarnedTransaction AS ETMain WHERE ETMain.UserID = @UserID_In
AND ETMain.ID = (
     SELECT MAX(ID)
     FROM EarnedTransaction AS ETSub
     WHERE ETSub.UserID = @UserID_In
     AND ETSub.TransactionType = 'Buying'
     AND ETSub.CompleteDate IS NULL );

现在不需要主别名(如果使用@UserID_In)

SET @UserID_In = 1;
DELETE FROM EarnedTransaction WHERE UserID = @UserID_In
AND ID = (
     SELECT MAX(ID)
     FROM EarnedTransaction AS ETSub
     WHERE ETSub.UserID = @UserID_In
     AND ETSub.TransactionType = 'Buying'
     AND ETSub.CompleteDate IS NULL );

然后是子集别名,并删除UserID上的双重条件:

SET @UserID_In = 1;
DELETE FROM EarnedTransaction WHERE ID = (
     SELECT MAX(ID)
     FROM EarnedTransaction
     WHERE UserID = @UserID_In
     AND TransactionType = 'Buying'
     AND CompleteDate IS NULL );

这里很容易检查子查询。