如何在mysql中编写这个特定的查询?

时间:2015-10-28 17:01:04

标签: mysql sql tsql elmah

我有一段SQL代码取自SQL Server下的ELMAH存储过程:

DELETE FROM [ELMAH_Error]
WHERE ErrorId NOT IN (SELECT TOP 100 ErrorId FROM ELMAH_Error ORDER BY TimeUtc DESC)

我现在迁移一个网站改为使用mysql,我不知道如何翻译这段代码。

我必须在这段代码之后添加翻译:

CREATE DEFINER=`b43638b86659eb`@`%` PROCEDURE `elmah_LogError`(
    IN ErrorId CHAR(36), 
    IN Application varchar(60), 
    IN Host VARCHAR(30), 
    IN Type VARCHAR(100), 
    IN Source VARCHAR(60), 
    IN Message VARCHAR(500), 
    IN User VARCHAR(50), 
    IN AllXml TEXT, 
    IN StatusCode INT(10), 
    IN TimeUtc DATETIME
)
    MODIFIES SQL DATA
BEGIN
    INSERT INTO `elmah_error` (
        `ErrorId`, 
        `Application`, 
        `Host`, 
        `Type`, 
        `Source`, 
        `Message`, 
        `User`, 
        `AllXml`, 
        `StatusCode`, 
        `TimeUtc`
    ) VALUES (
        ErrorId, 
        Application, 
        Host, 
        Type, 
        Source, 
        Message, 
        User, 
        AllXml, 
        StatusCode, 
        TimeUtc
    );
END

我尝试在END语句之前添加@Sick的响应,但是SQL Workbench(通过alter procedure命令)看不到它。

由于

4 个答案:

答案 0 :(得分:1)

等效的Sql Server TOP Mysql中的关键字是Limit,它应该在查询的末尾

DELETE FROM `ELMAH_Error`
WHERE ErrorId NOT IN (SELECT ErrorId 
                      FROM `ELMAH_Error`
                      ORDER BY TimeUtc DESC LIMIT 100)

答案 1 :(得分:0)

MySQL在某些子查询中不支持$ gcc main.c phy.c frm.c $ ./a.out Main. PHY stuff. Running phy_cb. phy_cb, default implementation. BAD!!! <--- not expected! FRM stuff. Running frm_cb frm_cb, APP implementation. GOOD 。如果是这种情况,那么使用显式连接:

limit

编辑:

上述代码假定DELETE e FROM ELMAH_Error e LEFT JOIN (SELECT ErrorId FROM ELMAH_Error ORDER BY TimeUtc DESC LIMIT 100 ) ee ON ee.ErrorId = e.ErrorId WHERE ee.ErrorId IS NULL; 在表格中是唯一的,并且没有ErrorId值。如果不是这样,那么查询将不起作用。 (注意:假设一个名为Id的列是唯一的而不是null似乎是非常合理的。)

NULL

答案 2 :(得分:0)

如果表格非常大,那么截断通常比MySQL中的删除要快得多。类似的东西:

lock tables ELMAH_Error write;
create temporary table cpy_ELMAH_Error 
   select * from ELMAH_Error order by TimeUtc DESC LIMIT 100;
truncate table ELMAH_Error;
insert into  ELMAH_Error select * from cpy_ELMAH_Error;
drop table cpy_ELMAH_Error;
unlock tables;

答案 3 :(得分:0)

There is one more somewhat simpler way if you are interested:

set @N=0;
delete from ELMAH_Error where (@N:=@N+1) > 101 order by TimeUtc DESC;