0
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 服务器版本相对应的手册,以AS ETMain WHERE ETMain.UserID = @UserID_In AND ETMain.ID = ( SELECT MAX(ID)在第 1 行附近使用正确的语法

4

2 回答 2

2

试试这个删除查询(“删除表”没有别名):

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 );
于 2014-09-29T09:28:51.500 回答
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 );

这里的子查询很容易检查。

于 2014-09-30T14:46:18.360 回答