1

I'll be brief:

WORKING

SELECT p.id,
    p.name,
    cat.name `category`,
    prod.name `producer`,
    p.images,
    p.price,
    p.flag_avaliable,
    p.amount,
    p.description,
    p.options
FROM product p
    INNER JOIN product_category cat ON cat.id = p.category_id
    INNER JOIN product_producer prod ON prod.id = p.producer_id
ORDER BY @asc_or_desc
    limit 5 offset 6;

NOT WORKING

set @asc_or_desc = 'id desc ';
set @limit_number = 5;
set @offset_number = 6;
SELECT p.id,
   p.name,
   cat.name  `category`,
   prod.name `producer`,
   p.images,
   p.price,
   p.flag_avaliable,
   p.amount,
   p.description,
   p.options
FROM product p
         INNER JOIN product_category cat ON cat.id = p.category_id
         INNER JOIN product_producer prod ON prod.id = p.producer_id
ORDER BY @asc_or_desc
limit @limit_number offset @offset_number;

So, I need the 'not working' version to work. How can I do that?

I have the same error: 'You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '@limit_number offset @offset_number; END''.

Why? Types are ok, you see... What the problem? Maybe values are substitute with some bug?

I'm using JetBrains DataGrip, MySQL 8.0.15.

4
  • Use dynamic SQL or built the query in the language of the client if there is any. Commented May 4, 2019 at 18:53
  • @stickybit, you mean prepared statements? Commented May 4, 2019 at 18:55
  • Yes, that's a possibility. Commented May 4, 2019 at 18:56
  • @stickybit, Ok, that works. I thought, sql has more might Commented May 4, 2019 at 18:59

1 Answer 1

1

Using prepared statements have solved the problem. The code:

set @statement =
    concat('SELECT p.id,
       p.name,
       cat.name  `category`,
       prod.name `producer`,
       p.images,
       p.price,
       p.flag_avaliable,
       p.amount,
       p.description,
       p.options
FROM product p
         INNER JOIN product_category cat ON cat.id = ?
         INNER JOIN product_producer prod ON prod.id = p.producer_id
ORDER BY id ',@asc_or_desc,'
limit ? offset ?');
prepare prepared from @statement;
EXECUTE prepared USING @category_id, @limit_number, @offset_number;
DEALLOCATE PREPARE prepared;
Sign up to request clarification or add additional context in comments.

1 Comment

@GordonLinoff, Yes, It doesn't work. Damn. How to fix it?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.