开发者

MySQL Stored Procedure | How to write it?

This time I have a MySQL question, I'm trying to create a stored procedure which will execute a prepared statement, the goal is to get a ranged list from a table("order_info"), the list is divided by "pages", each page is determined by a record count and should be ordered using a particular field sorted either 'ASC' or 'DESC', each record represents an "order" the catch here is that the procedure returns the orders of a particular group, the t开发者_如何学运维he order is associated to a user which belongs to a group. Here's what I've done so far:


    CREATE DEFINER=`root`@`%` PROCEDURE `getGroupOrders`(IN grp INT,
                                                   IN page INT, 
                                                   IN count INT, 
                                                   IN ord TINYINT, 
                                                   IN srt VARCHAR(4)
                                                   )
    BEGIN
        PREPARE prepGroupOrders FROM
        "SELECT oi.* FROM `dbre`.`order_info` oi
            INNER JOIN `dbre`.`users` usr 
            ON oi.`username` = usr.`username` AND usr.`id_group` = ?
            ORDER BY ? ? LIMIT ?, ?";

        SET @g := grp;
        SET @cnt := count;
        SET @start := @page*count ;
        SET @orderBy := ord;
        SET @sortBy := srt;

        EXECUTE prepGroupOrders USING @g,@orderBy,@sortBy,@start,@cnt;
    END

I get a syntax error when executing this, even though the editor does not higlight any errors and lets me save the procedure,I think that one of the follwing may be happening:

  • I am incorrectly usng the `ASC` or `DESC` since it is a SQL reserved word.
  • I read somewhere that Prepared statement are for only ONE SQL query, and since I have nested queries it can't be done.

I've tested this standard query:


    SELECT oi.* FROM `dbre`.`order_info` oi
        INNER JOIN `dbre`.`users` usr
        ON oi.`username` = usr.`username` AND usr.`id_group` = 1
    ORDER BY `status` DESC LIMIT 5, 10;

And it gives me the results I want. SO how would I design the procedure? Any help is truly appreciated.


This may not necessarily solve your issue but, you can probably clean that query up a bit, eliminate the subquery and get something that should perform a little better.

SELECT oi.* 
    FROM `dbre`.`order_info` oi
        INNER JOIN  `dbre`.`users` u
            ON oi.username = u.username
                AND u.id_group = 1
    ORDER BY `status` DESC 
    LIMIT 5, 10;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜